静态::与自我::-有没有缺点? [英] static:: vs. self:: - are there any downsides?

查看:93
本文介绍了静态::与自我::-有没有缺点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个StackOverflow问题中,我了解到self::不支持继承static::所在的位置(在PHP中).在类中定义一堆常量时,如果要覆盖子类中的这些常量以更改默认的行为",则必须使用static::,以便父类上的方法可以引用该常量,以表扬超越".

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

问了最初的问题以来的两年中,我开始广泛使用static::,以至于我很少使用self::,因为self::似乎会限制使用常量的类的可扩展性, static::没有此限制.

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.

即使我当前不打算在子类中覆盖常量,我还是会使用static::,以防万一-因此,我不必做一堆稍后进行搜索和替换,如果可以,我将要扩展该类并覆盖该常量.

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.

但是,在其他人的代码中,我很少看到static::的任何用法.直到2012年,我什至不知道它的存在.那么,为什么顺带一提,为什么通常不使用static::代替self::呢?

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?

那么我的问题是:与self::相对,使用static::引用类常量是否有明显的缺点?我在这里使用粗暴的反模式有罪吗?

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?

推荐答案

实际上,这仅取决于您所需的用途.如果需要访问要在其中调用的类的常量,请使用self.如果需要后期静态绑定,请使用static.

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.

从演奏的角度来看,selfstatic相当.

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.

要直接回答您的问题,我总是希望使用static进行测试(现在PHPUnit 4删除了对静态方法的支持).

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

这篇关于静态::与自我::-有没有缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆