【问题标题】:Calling methods and closures from an array从数组调用方法和闭包
【发布时间】:2016-04-13 23:18:51
【问题描述】:

在 JavaScript 中,你可以这样做:

var Module = (function () {
    var functions = [method1, method2]; // array of functions to execute

    function method1 () {
        console.log('calling method1');
    }

    function method2 () {
        console.log('calling method2');
    }

    function method3 () {
        console.log('calling method3');  // not called
    }

    function add (fn) {
        functions.push(fn); // add new function to the array
    }

    function printt () {
        for (var i in functions) functions[i](); // execute functions in the array
    }

    return {
        add: add,
        printt: printt
    };
})();

Module.add(function () {
    console.log('calling anonymous function');  
});

Module.printt();

// calling method1
// calling method2
// calling anonymous function

是否可以在 PHP 中做类似的事情,其中​​要执行的 (1) 方法存储在数组 (2) 中,并且可以添加新的函数/方法数组,这样当printt方法运行时,它会执行数组中的所有函数?

class Module {
    protected $functions = [];

    public function __construct () {
        // ?
    }

    protected function method1 () {
        echo 'calling method1';
    }

    protected function method2 () {
        echo 'calling method2';
    }

    protected function method3 () {
        echo 'calling method3';
    }

    public function add ($fn) {
        $this->functions[] = $fn;
    }

    public function printt () {
        foreach ($this->functions as $fn)  $fn();
    }
}

$module = new Module();

$module->add(function () {
    echo 'calling anonymous function';
});

$module->printt();

【问题讨论】:

  • PHP 有闭包吗?
  • 我相信根据这个页面Anonymous functions
  • 哇。我不知道。不错

标签: javascript php function methods


【解决方案1】:

检查is_callable() 是否有闭包,检查method_exists() 是否有对象的方法。

class Module {
    protected $functions = ['method1', 'method2'];

    // ...

    public function printt () {
        foreach ($this->functions as $fn) {
            if ( is_callable( $fn ) ) {
                $fn();
            } elseif ( method_exists( $this, $fn ) ) {
                $this->$fn();
            }
        }
    }
}

还有一个与 JS 不同的地方,就是你需要正确引用方法——通过对象中的 $this。

【讨论】:

  • 这就是我最初的想法。 “也许有不同的方法?”可能不会。谢谢。
【解决方案2】:

另一种方法是将成员方法作为可调用对象添加到函数数组中,而不仅仅是方法名称,然后使用 call_user_func 执行它们。

class Module {
  public function __construct() {
    $this->functions = [
      [$this, 'method1'],
      [$this, 'method2'],
    ];
  }

  // ...

  public function printt() {
    foreach($this->functions as $fn) {
      call_user_func($fn);
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-14
    • 2010-11-26
    • 2018-08-21
    • 2013-01-17
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多