如果我有这样的课程:
class MyClass {
protected function method1() {
// Method body
}
}
我可以以某种方式在变量中保存此方法的主体,因此我可以将其传递给应用程序吗?
例如:
class MyClass {
function __construct() {
$var = // body of method1
$something = new AnotherClass($var);
}
protected function method1($arg1, $arg2) {
// Method body
}
}
class AnotherClass {
function __construct($var) {
$var($this->arg1, $this->arg2);
}
}
我这样的事情可能吗?
答案 0 :(得分:0)
您可以尝试使用匿名函数:
$self = $this;
$var = function($arg1, $arg2) use (&$self) {
$self->method1($arg1, $arg2);
};
如此完整的例子:
class MyClass {
function __construct() {
$self = $this;
$var = function($arg1, $arg2) use (&$self) {
$self->method1($arg1, $arg2);
};
$something = new AnotherClass($var);
}
protected function method1($arg1, $arg2) {
// Method body
}
}
答案 1 :(得分:0)
您无法通过正文,但您可以将callable
引用传递给该函数:
...
new AnotherClass(array($this, 'method1'))
...
class AnotherClass {
function __construct(callable $var) {
$var($this->arg1, $this->arg2);
}
}
在这种情况下,该方法为protected
,因此AnotherClass
无法直接调用它。您可以使用匿名函数:
...
new AnotherClass(function ($arg1, $arg2) { return $this->method1($arg1, $arg2); })
...
匿名函数中的callable
类型提示和$this
仅适用于PHP 5.4,匿名函数仅适用于5.3+。对于任何以前的版本,解决方法或多或少都相当复杂。我怀疑这是多么好的解决方案,其他设计模式在这里可能更合适。