static:: vs. self:: - are there any downsides?
Asked Answered
F

1

8

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?

Falsecard answered 5/11, 2014 at 15:2 Comment(0)
M
2

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

Midshipman answered 5/11, 2014 at 15:10 Comment(3)
thanks for the answer! Why is "extensive usage of static" not a great idea? Please explain. Also, why is static preferable for testing purposes?Falsecard
there are lots of useful information about this topic: misko.hevery.com/2008/12/15/…Midshipman
I know PHP has moved on a lot since this question was posed but thought it was worth noting - self:: appears to inherit from the parent when used within a child class and, from the questions I've seen around this, apparently self:: in parent context does not get overridden by the child class. So static:: should be used in parent context but self:: is perfectly adequate in child context.Clarkin

© 2022 - 2024 — McMap. All rights reserved.