繁体   English   中英

如何调用分配给类的静态数组的函数?

[英]How can I call a function assigned to a class's static array?

我试图将一个函数添加到类中的静态变量中,然后从代码中的其他位置调用该函数。

有效

<?php

class MyClass {
    static $myVar = [];
    static function set_myVar($function) {
        self::$myVar[] = $function;
    }
}

MyClass::set_myVar(function () { echo 'hello world!'; });
$t = MyClass::$myVar[0];
$t();

?>

但是,这不是

<?php

class MyClass {
    static $myVar = [];
    static function set_myVar($function) {
        self::$myVar[] = $function;
    }
}

MyClass::set_myVar(function () { echo 'hello world!'; });
MyClass::$myVar[0]();

?>

它导致以下错误:

注意:未定义的变量:第11行的C:\\ xampp \\ htdocs \\ public \\ index.php中的myVar

致命错误:函数名称必须是第11行上C:\\ xampp \\ htdocs \\ public \\ index.php中的字符串

谁能告诉我为什么?

PHP解释器在引用类中的静态数组之前尝试评估$myVar[0]()

你可以测试一下

$myVar = ["set_myVar"];

在出现错误之前,您会得到:

Warning: Missing argument 1 for MyClass::set_myVar()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM