是否可以将类方法的主体存储在变量中


Is it possible to store body of class method in a variable?

如果我有一个这样的类:

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);
    }
}

我有这样的可能吗?

您不能传递正文,但可以传递对该函数的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+中可用。对于任何以前的版本,解决方法都或多或少相当复杂。我怀疑这个解决方案到底有多好,不过其他设计模式在这里可能更合适。

您可以尝试使用匿名函数:

$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
    }
}