Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static:: vs. self:: - are there any downsides?

In this StackOverflow question I learned that self:: was not inheritance-aware where static:: was (in PHP). When it comes to defining a bunch of constants within a class, if you want to override those constants in a subclass to change default "behaviours", it becomes necessary to use static:: so that a method on the parent class that references the constant, honours the "override".

In the 2 years since I asked that original question, I have started using static:: extensively, to the point that I rarely use self:: since self:: would appear to limit the extensibility of a class that uses constants, where static:: does not have this limitation.

Even if i don't currently intend a constant to be overridden in a child class, I end up using static::, just in case - so I don't have to do a bunch of search-and-replace later, if it turns out I will want to extend the class and override the constant.

However, in others' code, I rarely see any use of static::. To the point that, up until 2012, I didn't even know it existed. So why is it not a general practice to use static:: in the place of self:: as a matter of course?

My question, then, is: are there any obvious downsides to using static:: for refering to class constants, as opposed to self::? Am I guilty of using a gross anti-pattern here?

like image 690
Tom Auger Avatar asked Nov 09 '22 23:11

Tom Auger


1 Answers

Actually it depends only on the use you need. If you need to access the constant of the class in which you are calling it, use self. If you need late static binding use static.

From the point of view of performances, self and static are pretty equivalent.

Also be aware that extensive usage of static combined to override/inheritance is not a great idea.

For a direct answer to your question, I would always prefer the use of static for testing purpose (altho now PHPUnit 4 removed the support for mocking static methods).

like image 172
dynamic Avatar answered Nov 14 '22 22:11

dynamic