3

Is there any way to access a static variable of a PHP class without using the class prefix?

Example:

class A {

   protected static $x = "blahblah";

   public static function p() {

       print(A::$x); // <= Is there no way to omit A:: ???

   }

}

I understand, that at that point $x could be an uninitialized local variable, but it would make a lot of sense to be able to say/declare/set that in these cases the interpreter should resolve $x as the member declared earlier. Typing the class prefix everywhere is a major fail IMHO.

1
  • 1
    self::$x works from within the class Commented Jan 6, 2013 at 14:17

1 Answer 1

5

If the method you're using it from is in the same class, you can use self:: or static::.

E.g.:

class A {

   protected static $x = "blahblah";

   public static function p() {

       print(self::$x);

   }

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

2 Comments

Thanks for your answer, however my point was to skip typing the prefix every time... :)
Well, self:: and static:: save you from having to refactor every reference to the variable inside the class if you ever change the class's name, but I don't think there's a way to reference static variables without specifying the class in some way (be it the class's name or self:: or static::).

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.