[英]How can I call a function assigned to a class's static array?
I am trying to add a function to a static variable in a class, and then call that function from elsewhere in my code. 我试图将一个函数添加到类中的静态变量中,然后从代码中的其他位置调用该函数。
This works : 这有效 :
<?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();
?>
However, this does not : 但是,这不是 :
<?php
class MyClass {
static $myVar = [];
static function set_myVar($function) {
self::$myVar[] = $function;
}
}
MyClass::set_myVar(function () { echo 'hello world!'; });
MyClass::$myVar[0]();
?>
It results in the following error: 它导致以下错误:
Notice: Undefined variable: myVar in C:\\xampp\\htdocs\\public\\index.php on line 11 注意:未定义的变量:第11行的C:\\ xampp \\ htdocs \\ public \\ index.php中的myVar
Fatal error: Function name must be a string in C:\\xampp\\htdocs\\public\\index.php on line 11 致命错误:函数名称必须是第11行上C:\\ xampp \\ htdocs \\ public \\ index.php中的字符串
Can anyone tell me why? 谁能告诉我为什么?
The PHP interpreter tries to evaluate $myVar[0]()
before referencing the static array in your class. PHP解释器在引用类中的静态数组之前尝试评估$myVar[0]()
。
You can test it if you place 你可以测试一下
$myVar = ["set_myVar"];
before your error and you get: 在出现错误之前,您会得到:
Warning: Missing argument 1 for MyClass::set_myVar()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.