繁体   English   中英

如何在类中的php中调用变量函数?

[英]How to call a variable function in php within a class?

我有以下示例代码

<?php

class Test {
    function foo() {
        print "foo\n";
    }

    function bar() {
        $func = 'foo';
        $func();
    }
}

$test = new Test();
$test->bar()

它调用$test-bar() ,在内部调用一个名为foo的可变php函数。 这个变量包含字符串foo ,我希望像这里一样调用foo函数。 而不是获得预期的输出

foo

我收到一个错误:

PHP Fatal error:  Call to undefined function foo()  ...

在函数名称中使用字符串时,如何正确执行此操作? 字符串“ func”可能表示实际代码中类范围内的几个不同函数。

根据文档 ,以上内容应该像我编写的代码一样工作,或多或少...

<?php

class Test {
    public function foo() {
        print "foo\n";
    }

    public function bar() {
        $func = 'foo';
        $this->$func();
    }
}

$test = new Test();
$test->bar();

?>

使用它来访问此类的当前功能

您使用关键字$this

<?php

class Test {
    function foo() {
        print "foo\n";
    }

    function bar() {
        $this->foo(); //  you can do this

    }
}

$test = new Test();
$test->bar()

有两种从字符串输入中调用方法的方法:

$methodName = "foo";
$this->$methodName();

或者您可以使用call_user_func_array()

call_user_func_array("foo",$args); // args is an array of your arguments

要么

call_user_func_array(array($this,"foo"),$args); // will call the method in this scope

您可以做的是使用函数call_user_func()调用回调。

<?php

class Test {
    public function foo() {
        print "foo\n";
    }

    public function bar() {
        $func = 'foo';
        call_user_func(array($this, $func));
    }
}

$test = new Test();
$test->bar();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM