Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 我可以使用变量来调用方法吗?_Php_Oop_Codeigniter - Fatal编程技术网

Php 我可以使用变量来调用方法吗?

Php 我可以使用变量来调用方法吗?,php,oop,codeigniter,Php,Oop,Codeigniter,当方法名存储在变量中时,我可以调用方法吗?语法是什么?假设我有以下PHP代码: class MyClass { public $default; function index() { /* call method named by $this->default */ } function method_1() {} function method_2() {} ... } 如果没有专门调用其他方法,则在初始化类时默认调用i

当方法名存储在变量中时,我可以调用方法吗?语法是什么?假设我有以下PHP代码:

class MyClass {
    public $default;

    function index() {
        /* call method named by $this->default */
    }
    function method_1() {}
    function method_2() {}
    ...
}
如果没有专门调用其他方法,则在初始化类时默认调用
index()

如何使用
MyClass->$default
属性从
index()
中调用其中一个方法?也就是说,如果我通常写:

function index() { $this->method_1(); }
我可以使用默认变量调用正确的方法吗

我可以使用变量来调用方法吗

是的,你可以。例如,在对象内部:

$method = "method_1";

if (method_exists($this, $method))
 $this->{$method}();
我可以使用变量来调用方法吗

是的,你可以。例如,在对象内部:

$method = "method_1";

if (method_exists($this, $method))
 $this->{$method}();

是,您可以使用以下语法:

$methodname = 'method_1';
$this->$methodname();

是,您可以使用以下语法:

$methodname = 'method_1';
$this->$methodname();
还有解决办法:

call_user_func( array($this,$methodname), $arg...);
还有解决办法:

call_user_func( array($this,$methodname), $arg...);
看一看