Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

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

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);
    }
}
like image 462
akTed Avatar asked Nov 29 '25 05:11

akTed


1 Answers

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.

like image 97
Tchoupi Avatar answered Nov 30 '25 17:11

Tchoupi