Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Can static:: replace self::?

I am a little confused with this matter. I am designing an ORM class that tries to behave very similarly to ActiveRecord in ruby on rails, but that's beside the point.

What I'm trying to say is that my class makes extensive use of static attribute inheritance, specially for database and table handling. My question is, should I use self:: at all?

like image 804
elite5472 Avatar asked Jan 17 '11 22:01

elite5472


People also ask

Can static methods be Redeclared?

Yes there's a workaround: use another name. ;-) PHP is not C++, methods are unique by their names, not by their name/arguments/visibility combination. Even then, you cannot overload an object method to a static method in C++ either.

What does self :: mean in PHP?

self operator: self operator represents the current class and thus is used to access class variables or static variables because these members belongs to a class rather than the object of that class.

What is difference between self and static in PHP?

self Vs static: The most basic difference between them is that self points to the version of the property of the class in which it is declared but in case of static, the property undergoes a redeclaration at runtime.

What is static :: PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.


1 Answers

You have to ask yourself: "Am I targeting the problem with the adequated approach?"

self:: and static:: do two different things. For instance self:: or __CLASS__ are references to the current class, so defined in certain scope it will NOT suffice the need of static calling on forward.

What will happen on inheritance?

class A {     public static function className(){         echo __CLASS__;     }      public static function test(){         self::className();     } }  class B extends A{     public static function className(){         echo __CLASS__;     } }  B::test(); 

This will print

A 

In the other hand with static:: It has the expected behaviour

class A {     public static function className(){         echo __CLASS__;     }      public static function test(){         static::className();     } }  class B extends A{     public static function className(){         echo __CLASS__;     } }   B::test(); 

This will print

B 

That is called late static binding in PHP 5.3.0. It solves the limitation of calling the class that was referenced at runtime.

With that in mind I think you can now see and solve the problem adequately. If you are inheriting several static members and need access to the parent and child members self:: will not suffice.

like image 159
DarkThrone Avatar answered Sep 22 '22 09:09

DarkThrone