3

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);
    }
}
2
  • try call_user_func(self::$static_var, $passed_var) Commented Feb 1, 2013 at 20:53
  • Sorry, @Shikiryu. I edited the Question for you. Commented Feb 1, 2013 at 21:09

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I edited my Question to be more specific. I'm not trying to look for a work around (as I've already outlined one), I'm just trying to understand why Test 1 doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.