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

三世轮回 提交于 2019-12-07 13:18:48

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/26760331/static-vs-self-are-there-any-downsides

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!