我需要调用对象内部的函数,类中的函数。当然,对于“动态”类方法,我可以使用__call & __set magics来调用它,但在本例中不能这样做。下面是这种情况的例子。
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->fn 1()?如果没有,有什么建议没有大幅度的改变吗?
不幸的是,这不是JavaScript,也不喜欢这个类的处理方式,但是我必须尝试一下
发布于 2019-09-18 12:23:41
在这种情况下,唯一简单的解决方法是在匿名类中更改对象。在此过程中,您必须使用类似的变量名"$_this“将主类的作用域存储在内部匿名类(Es)上。
class mainclass
{
public $v1 = "Hello";
public $fn = null;
function __construct( )
{
$this->fn = new class( $this)
{
public $_this = null;
public function __construct( $mainscope )
{
$this->_this = &$mainscope;
}
public function __call( $method, array $args )
{
if ( isset( $this->{ $method } ) )
{
return call_user_func_array( $this->$method, $args );
}
elseif ( isset( $this->_this->{ $name } ) )
{
return call_user_func_array( $this->_this->{ $name }, $args);
}
}
public function __set( $name, $value )
{
$this->{ $name } = is_callable( $value ) ? $value->bindTo( $this, $this ) : $value;
}
};
}
public function __call( $method, array $args )
{
return call_user_func_array( $this->{ $method }, $args );
}
public function __set( $name, $value )
{
$this->{ $name } = is_callable( $value ) ? $value->bindTo( $this, $this ) : $value;
}
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->_this->v1 . " World :)";
};
$main->fn3(); // This of course works!
$main->fn4(); // Even this works!
$main->fn->fn1(); //Hello World :)结果并不是很难看,而且也是可管理的。无论如何,是目前唯一的选择。
发布于 2019-09-18 10:30:32
$main->fn->fn1();fn1是一个属性,尝试使用$main->fn。
发布于 2019-09-18 10:32:16
($main->fn->fn1)();应该在工作。但是,您不能在匿名函数中访问$this
https://stackoverflow.com/questions/57990414
复制相似问题