self :: vs className ::在PHP的静态className方法中 [英] self:: vs className:: inside static className methods in PHP
问题描述
我想个人偏好可能没有什么区别,但是当阅读各种PHP代码时,我遇到了两种访问方法类的方法。
I guess there may not be any difference but personal preference, but when reading various PHP code I come across both ways to access the methods class.
什么是区别:
class Myclass
{
public static $foo;
public static function myMethod ()
{
// between:
self::$foo;
// and
MyClass::$foo;
}
}
推荐答案
(注意:最初的版本说没什么区别。实际上是有区别的。
(Note: the initial version said there was no difference. Actually there is)
确实有一个小差别。 self ::
转发静态呼叫,而 className ::
不转发静态呼叫。这仅适用于PHP 5.3+中的后期静态绑定。
There is indeed a small diference. self::
forwards static calls, while className::
doesn't. This only matters for late static bindings in PHP 5.3+.
在静态调用中,PHP 5.3+会记住最初调用的类。使用 className ::
使PHP忘记该值(即,将其重置为 className
),而 self :: 保留它。考虑:
In static calls, PHP 5.3+ remembers the initially called class. Using className::
makes PHP "forget" this value (i.e., resets it to className
), while self::
preserves it. Consider:
<?php
class A {
static function foo() {
echo get_called_class();
}
}
class B extends A {
static function bar() {
self::foo();
}
static function baz() {
B::foo();
}
}
class C extends B {}
C::bar(); //C
C::baz(); //B
这篇关于self :: vs className ::在PHP的静态className方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!