PHP 通过变量动态调用 class 函数捕获异常
PHP calling class function dynamically by variables caughts exception
我正在尝试使用变量 (php7) 调用 class 的 public 函数。因此我这样做:
$module = 'frontend\modules\rest\models\Member';
$action = 'view_profile'
$response = new $module();
$response = $response1->$action;
通过调用 $response1->$action 我得到以下错误:
Undefined property: frontend\modules\rest\models\Member::$view_profile
我看到系统尝试调用 ...Member\$view_profile 但这行不通。但是为什么view_profile前面的'$'呢?我尝试了几种变体,但 $view_profile 的错误始终存在。这种方法有什么问题?
查看其他回复:OOP in PHP: Class-function from a variable?(无法发表评论,抱歉...)
无论如何,这就是你想要的:http://php.net/manual/en/functions.variable-functions.php
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
所以我想唯一缺少的是
之后的“()”
$response1->$action;
我正在尝试使用变量 (php7) 调用 class 的 public 函数。因此我这样做:
$module = 'frontend\modules\rest\models\Member';
$action = 'view_profile'
$response = new $module();
$response = $response1->$action;
通过调用 $response1->$action 我得到以下错误:
Undefined property: frontend\modules\rest\models\Member::$view_profile
我看到系统尝试调用 ...Member\$view_profile 但这行不通。但是为什么view_profile前面的'$'呢?我尝试了几种变体,但 $view_profile 的错误始终存在。这种方法有什么问题?
查看其他回复:OOP in PHP: Class-function from a variable?(无法发表评论,抱歉...)
无论如何,这就是你想要的:http://php.net/manual/en/functions.variable-functions.php
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
所以我想唯一缺少的是
之后的“()”$response1->$action;