Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Static properties using PHP object

Tags:

php

static

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

like image 635
user2314576 Avatar asked Jun 14 '13 11:06

user2314576


People also ask

Can an object access static variables?

static variables are otherwise called as class variables, because they are available to each object of that class. As member is an object of the class Static, so you can access all static as wll as non static variables of Static class through member object.

How do you call a static property?

To call a static method, you write the class name, followed by 2 colons (::) followed by the method name, which includes the parentheses ().

How can we create static property and class method in PHP?

to use static propery inside any method of the same class, use self keyword instead of -> operator that is used for accessing instance properties. <? php class testclass{ static $name="test"; public function test(){ echo self::$name; } } $obj=new testclass(); $obj->test(); ?>

How use $this in static method in PHP?

You can't use $this inside a static function, because static functions are independent of any instantiated object. Try making the function not static. Edit: By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.


3 Answers

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

like image 175
Robert Avatar answered Oct 23 '22 09:10

Robert


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

like image 33
deceze Avatar answered Oct 23 '22 09:10

deceze


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

like image 2
Alp Altunel Avatar answered Oct 23 '22 10:10

Alp Altunel