I'm new to using static methods & properties in classes. What I'm trying to do is run a variable function, but can't use:
self::$static_var()
PHP throws a notice:
Undefined variable: static_var
I have to first assign to a local variable like so:
$local_var = self::$static_var;
Then I can do
$local_var();
Here's some example code. I don't understand why Test 1 doesn't work. I have to do Test 2 in order to get the desired functionality. Question: Why is it that Test 1 doesn't work?
X::do_stuff('whatever');
class X {
public static $static_var = 'print_r';
public static function do_stuff($passed_var) {
self::$static_var($passed_var);
}
}
X::do_stuff('whatever');
class X {
public static $static_var = 'print_r';
public static function do_stuff($passed_var) {
$local_var = self::$static_var;
$local_var($passed_var);
}
}
Use call-user-func:
call_user_func(self::$static_var, $passed_var);
Concerning your edited question:
I tried to find an explanation in PHP docs. It is probably because $static_var is not yet evaluated when the function call is processed. But the best answer to your question is probably: because it's the way it is. A good example is: $classname::metdhod(); was not valid before PHP 5.3. Now it is. There is really no reason why. You should ask the PHP guys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With