codeigniter - PHP 参数不定,如何动态调用方法?

WBOY
Release: 2016-06-06 20:24:22
Original
1245 people have browsed it

如:
我现在有三个方法

<code>foo($a,$b=null)

boo($a=array(),$b="")

Roo($a)
</code>
Copy after login
Copy after login

现在我只需要传递方法名称和参数列表就能直接调用方法。

希望是可以这样(伪代码):

<code>function run_function($fun_name,$paras)
{
    {$fun_name}(....//这里应该怎么写呢?);
}
</code>
Copy after login
Copy after login

自己找到正确答案了,谢谢下面两个回复的,但真不是我需要的答案。现贴出解决方案:

<code>$handler = array( 'test', 'test3');
$params = array(
    array(1,2,3,4),
    1
);

if($params == null)
{
    call_user_func($handler);
}
if (is_callable($handler) )
{
    call_user_func_array( $handler , $params );
}


class test
{
    function test1($arr,$arr1)
    {
        var_dump(array_merge($arr,$arr1));
    }

    function test2()
    {
        echo 123;
    }

    function  test3($arr,$a)
    {
        var_dump($arr);
        var_dump($a);
    }
}</code>
Copy after login
Copy after login

回复内容:

如:
我现在有三个方法

<code>foo($a,$b=null)

boo($a=array(),$b="")

Roo($a)
</code>
Copy after login
Copy after login

现在我只需要传递方法名称和参数列表就能直接调用方法。

希望是可以这样(伪代码):

<code>function run_function($fun_name,$paras)
{
    {$fun_name}(....//这里应该怎么写呢?);
}
</code>
Copy after login
Copy after login

自己找到正确答案了,谢谢下面两个回复的,但真不是我需要的答案。现贴出解决方案:

<code>$handler = array( 'test', 'test3');
$params = array(
    array(1,2,3,4),
    1
);

if($params == null)
{
    call_user_func($handler);
}
if (is_callable($handler) )
{
    call_user_func_array( $handler , $params );
}


class test
{
    function test1($arr,$arr1)
    {
        var_dump(array_merge($arr,$arr1));
    }

    function test2()
    {
        echo 123;
    }

    function  test3($arr,$a)
    {
        var_dump($arr);
        var_dump($a);
    }
}</code>
Copy after login
Copy after login

http://www.php.net/manual/zh/function.func-get-args.php

<code>function run_function($fun_name)
{
    if(function_exists($fun_name))
    {
        $num = func_num_args();        
        $args = func_get_args();
        array_shift($args);
        return $num==1 ? call_user_func($fun_name) : call_user_func_array($fun_name,$args);
    }
    trigger_error('Call to undefined function ' . $fun_name, E_USER_ERROR);
}
//使用
run_function('foo', $a, $b);
run_function('boo', $a, $b);
run_function('Roo', $a);</code>
Copy after login

被忽略的回答可以实现阿 真是醉了

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!