Reputation: 2682
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?
Upvotes: 0
Views: 36
Reputation: 479
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()
Upvotes: 1