PHP: Why can't a static variable in a class be used as a variable?

I am new to using static methods and properties in classes. I am trying to execute a variable function , but cannot use:

self::$static_var()

      

PHP issues a notification:

Undefined variable: static_var

      

I need to first assign a local variable like this:

$local_var = self::$static_var;

      

Then I can do

$local_var();

      

Here's some sample code. I don't understand why Test 1 is not working. I need to do Test 2 to get the functionality I want . Question: Why Test 1 doesn't work to work?

Test 1 - not working

X::do_stuff('whatever');

class X {
    public static $static_var = 'print_r';

    public static function do_stuff($passed_var) {
        self::$static_var($passed_var);
    }
}

      

Test 2 - works

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);
    }
}

      

+3


source to share


1 answer


Use call-user-func

:

call_user_func(self::$static_var, $passed_var);

      



Regarding your edited question:

I tried to find an explanation in the PHP docs. Probably because it $static_var

is not yet evaluated when processing a function call. But the best answer to your question is probably because it is. Good example: $classname::metdhod();

not valid until PHP 5.3. Now this. There is no reason for this. You have to ask PHP guys.

+3


source







All Articles