javascript - 从数组调用方法和闭包

标签 javascript php function methods

在 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();

最佳答案

检查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 正确引用该方法。

关于javascript - 从数组调用方法和闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36611197/

相关文章:

javascript - 为什么非静态变量的行为类似于静态变量?

C++:在这种情况下引用的优势是什么?

javascript - FF 可以播放 mp3,但不能使用 javascript Audio API

javascript - 如何随机生成一个介于 -0.5 和 0.5 之间的数字?

php - "ppa.launchpad.net/ondrej/php/ubuntu focal/main amd64 Packages"-404 未找到

php - 将mysql数据库导出到excel

javascript - 如何将 Ajax 响应转换为字符串以与 JS 字符串进行比较

R 中的函数,传递数据框和列名

javascript - 根据选择显示不同的表单域

javascript - Reactjs。无法将变量传递给类