【发布时间】:2020-01-19 06:31:59
【问题描述】:
我需要调用一个对象内部、类内部的函数。当然,对于“On The Fly”类方法,我可以使用 __call 和 __set 魔法来调用它,但在这种情况下不能。以下是这种情况的示例。
class mainclass
{
public $v1 = "Hello";
public $fn = null;
function __construct( )
{
$this->fn = (object) [ "fn1" => null,
"fn2" => null,
];
}
public function __call( $name, array $args )
{
return call_user_func_array( $this->$name, $args );
}
public function fn3()
{
echo "This of course works! <br />";
}
}
$main = new mainclass();
$main->fn4 = function()
{
echo "Even this works! <br />";
};
$main->fn->fn1 = function()
{
echo $this->v1 . " World :)";
};
$main->fn3(); // This of course works!
$main->fn4(); // Even this works!
$main->fn->fn1(); //Call to undefined method stdClass::fn1()
有可能以这种方式调用函数“f1”: $main->fn->fn1() ? 如果没有,有没有大刀阔斧的建议?
不幸的是,这不是 JavaScript,不喜欢处理此类的方式,但我必须尝试一下
【问题讨论】:
-
如果一个函数/闭包在您需要调用它之前存储在
$a->fn->fn1中,它应该可以正常工作。如果是null,请尝试自行添加 -
目前,我唯一的解决方案是使用命名前缀“fn_”并将函数直接“附加”到主类上:$main->fn_f1 = function() { .. .. };欢迎提出建议!