Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any <good> reason or use case to use the self keyword in php instead of static keyword?

Tags:

oop

php

As of php 5.3, the static keyword resolved the late static binding issue and it can be used like most other OO languages use self. In PHP self still exists.

I know how the two keywords are separate functionally as previously pointed out in this question: Is there any reason to use the self keyword?.

However, my question is: Can anyone give a reason why you would want to use self in code meant to run only with 5.3 or later PHP? Does self have better performance? I've yet to find any compelling use case for using the self keyword anymore. My understanding is it only remains to allow old libraries to continue working in an expected manner.

The key to the question is can anyone suggest a good reason, ANY GOOD REASON, just one, tiny, little, reason that makes sense for a competent PHP developer to say "Gee, here I should really use 'self' instead of 'static'."

Because you might want to shoot yourself in the foot and that's a reason to use it isn't a good reason.

like image 521
Ray Avatar asked Aug 31 '25 22:08

Ray


1 Answers

Ah! Found my one good reason. At the moment in php 5.3 you cannot access compile time constants with static.

The code below will throw an error

 class Foo{
      const BAR = "FREE BEER";

      public static function whatDoWeLove(){
          return static::BAR;
      }
 }


 echo Foo::whatDoWeLove();

The error I get is:

PHP Fatal error:  "static::" is not allowed in compile-time constants in....

So, I guess for now self limps along until that changes or PHP adds the ability to use the final keyword with static properties. Drats.

like image 172
Ray Avatar answered Sep 03 '25 12:09

Ray