0
我想將一個函數添加到類中的靜態變量,然後從我的代碼中的其他地方調用該函數。如何調用分配給類的靜態數組的函數?
這工作:
<?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]();
?>
這將導致以下錯誤:
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
誰能告訴我爲什麼?