PHP可以static ::代替self ::吗? [英] PHP Can static:: replace self::?
问题描述
我对此事有点困惑.我正在设计一个ORM类,它的行为与ActiveRecord在ruby on rails上非常相似,但这不重要.
I am a little confused with this matter. I am designing an ORM class that tries to behave very similarly to ActiveRecord in ruby on rails, but that's beside the point.
我要说的是,我的类广泛使用静态属性继承,特别是用于数据库和表处理.我的问题是,我应该完全使用self ::吗?
What I'm trying to say is that my class makes extensive use of static attribute inheritance, specially for database and table handling. My question is, should I use self:: at all?
推荐答案
您必须问自己:我要采用适当的方法来解决问题吗?"
You have to ask yourself: "Am I targeting the problem with the adequated approach?"
self::
和static::
做两个不同的事情.例如,self::
或__CLASS__
是对当前类的引用,因此在一定范围内进行定义将无法满足对向前进行静态调用的需要.
self::
and static::
do two different things. For instance self::
or __CLASS__
are references to the current class, so defined in certain scope it will NOT suffice the need of static calling on forward.
继承会发生什么?
class A {
public static function className(){
echo __CLASS__;
}
public static function test(){
self::className();
}
}
class B extends A{
public static function className(){
echo __CLASS__;
}
}
B::test();
这将打印
A
另一方面,它具有预期的行为
In the other hand with static::
It has the expected behaviour
class A {
public static function className(){
echo __CLASS__;
}
public static function test(){
static::className();
}
}
class B extends A{
public static function className(){
echo __CLASS__;
}
}
B::test();
这将打印
B
这称为 后期静态绑定在PHP 5.3.0中.它解决了调用在运行时引用的类的局限性.
That is called late static binding in PHP 5.3.0. It solves the limitation of calling the class that was referenced at runtime.
考虑到这一点,我认为您现在可以充分看到并解决问题了.如果您要继承几个静态成员,并且需要访问父成员和子成员,则self::
将无法满足要求.
With that in mind I think you can now see and solve the problem adequately. If you are inheriting several static members and need access to the parent and child members self::
will not suffice.
这篇关于PHP可以static ::代替self ::吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!