在PHP中的变量中存储对类函数的引用


Storing a reference to a class function in a variable in PHP

这里是一个假设的例子(父类PageState包含类FooterState的实例-根据条件,该实例可能不会创建。FooterState需要调用一个在PageState类中创建的公共函数):

class PageState {
    private $footer_state = null;
    function PageState() {
        $this->footer_state= new FooterState($this);
    }
    public function getExpectedPageDimensions() {
        // do calculations based on existing body content
        return $dimensions;
    }
}
class FooterState {
    private $get_dimensions_func = null;
    function FooterState($page_state) {
        // Here, we need to get the reference to the function from the $page_state class
        $this->get_dimensions_func = $page_state->getExpectedPageDimensions;
    }
    public function addLogos($logo_data) {
        $page_dimensions = $this->get_dimensions_func();
        // use the page dimensions to decide on the size of the content
        return Array('width' => $width, 'height' => $height);
}

我知道其他解决方案:

  • 与其复制对函数的引用,不如创建对类$this->page_state = $page_state;的引用,然后FooterState中的函数可以调用$this->page_state->getExpectedPageDimensions();
  • 使用global $PageStateInstance;,然后只调用$PageStateInstance->getExpectedPageDimensions();

但我想知道是否有可能将对类函数的引用存储在变量中。如果函数在类之外,则可以执行$func = 'getExpectedPageDimensions'; $func();之类的操作。

您可以将一个实例和一个函数作为可调用传递:一个带有实例和函数名的数组。有一个类似的系统用于调用静态类方法。

# An example callback method
class MyClass {
    function myCallbackMethod() {
        echo 'Hello World!';
    }
}
# create an instance
$obj = new MyClass();
# and later:
call_user_func(array($obj, 'myCallbackMethod'));

从这里的文档:http://php.net/manual/en/language.types.callable.php

与其复制对函数的引用,不如创建对类$this->page_state=$page_state的引用;然后FooterState中的函数可以调用$this->page_state->getExpectedPageDimensions();

这是最好的通用解决方案。

但我想知道是否有可能将对类函数的引用存储在变量中。

是的,但它实际上只适用于静态函数,除非实例化该类。示例:

class A {
    public static function doSomethingStatic() {
        // ...
    }
    public function doSomethingElse() {
        // ...
    }
}
$somevar = 'A::doSomethingStatic';
$result = call_user_func($somevar); // calls A::doSomethingStatic();
$myA = new A();
$myref = array($myA, 'doSomethingElse');
$result = call_user_func($myref); // calls $myref->doSomethingElse();

请注意,在第二个示例中,您必须实例化类,并将数组作为第一个参数传递给call_user_func()

参考文献:http://php.net/manual/en/function.call-user-func.php和http://php.net/manual/en/language.types.callable.php

可以存储对类函数的引用

我认为你指的是对象而不是,但是的,你可以,用闭包。

不过我认为你不需要。$this->page_state似乎可以正常工作。

不要使用全局变量。