25

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..

Community
  • 1
  • 1
user2314576
  • 287
  • 1
  • 4
  • 6
  • also, from inside a class you may use `self::$my_static` or `static::$my_static` (see [late static bindings](http://php.net/manual/en/language.oop5.late-static-bindings.php) for the `static::` usage (since PHP 5.3) – Carlos Campderrós Jun 14 '13 at 11:55
  • check this link it may help... http://php.net/manual/en/language.oop5.static.php – Muhammad Saqlain Arif Jun 14 '13 at 12:03

3 Answers3

25

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

Robert
  • 19,800
  • 5
  • 55
  • 85
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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 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'? – BLaZuRE Jun 14 '13 at 12:01
  • Sometimes when you hold name of classes in strings and you're doing dynamic operations of them it's very useful. – Robert Jun 14 '13 at 12:03
  • @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 Jun 14 '13 at 12:08
  • 1
    @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 – deceze Jun 14 '13 at 12:11
3

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

Alp Altunel
  • 3,324
  • 1
  • 26
  • 27