26

This is with reference to Get a static property of an instance, I am a newbie and have the following code :

class Foo
{
   public static $my_static = 1;
}

class Bar extends Foo
{

}

$foo = new Foo();
$boo = new Bar();

echo Foo::$my_static;  // ok
echo Bar::$my_static;  // ok
echo $foo::$my_static; // ok
echo $boo::$my_static; // ok

Static variables/properties are accessed only as ClassName::static_property as in C++, but it is not the case in PHP... but PHP books mostly mention the className::static_property pattern, not the object::static_property construct. Need more light on this..

2

3 Answers 3

26

Static properties may be accessed on various ways.

Class::$aStaticProp; //by class name

$classname::$aStaticProp; // As of PHP 5.3.0 by object instance

Static properties cannot be accessed through the object using the arrow operator ->.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

More you can read in manual

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

Comments

12

$instance::$staticProperty is simply a convenience shorthand for Class::$staticProperty. Since you already have an instance of a class and the syntax is unambiguous, PHP saves you from writing a potentially long class name. There's no functional difference.

4 Comments

I do have a followup annoyance, since I'm a bit in disbelief that this works: $instance::$staticProperty does not make sense to me. The static property belongs to the class, not the object. Why does the interpreter allow this to slide for 'convenience'?
Sometimes when you hold name of classes in strings and you're doing dynamic operations of them it's very useful.
@Robert I guess it should make sense to me because PHP isn't the strictest of languages, but you could simply use get_class() to get the object's class name.
@BLaZuRE $foo::$bar"Get the static property $bar of the class $foo is an instance of." It's just syntactic sugar and seems mightily convenient to me. :-3
3

within the class you have to use like self::$staticPropery if the function accessing to the variable is also static.

Comments

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.