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
Fatal error: Function name must be a string in C:\\xampp\\htdocs\\public\\index.php on line 11
Can anyone tell me why?
The PHP interpreter tries to evaluate $myVar[0]()
before referencing the static array in your class.
You can test it if you place
$myVar = ["set_myVar"];
before your error and you get:
Warning: Missing argument 1 for MyClass::set_myVar()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.