我知道static ::和self :: like在这个例子中有区别(从
https://stackoverflow.com/a/13613718/2342518开始)
class One
{
const TEST = "test1";
function test() { echo static::TEST; }
}
class Two extends One
{
const TEST = "test2";
}
$c = new Two();
$c->test();
当使用static :: TEST时返回test2,当使用self :: TEST时返回test1.
但是当使用$this :: TEST时它也会返回test2.
static :: TEST可以在静态方法中使用,而$this :: TEST在使用之前需要一个实例(因此在静态方法中不可用).
但是如果不能在静态方法中使用$this ::,则static ::可以在非静态方法中使用(如示例中所示).
那么,static ::和$this ::在非静态方法中有什么区别?
可选的完整测试
abstract class AOne
{
const TEST = "test1";
abstract public function test();
}
class OneStatic extends AOne
{
public function test()
{
return static::TEST;
}
}
class TwoStatic extends OneStatic
{
const TEST = "test2";
}
class OneSelf extends AOne
{
public function test()
{
return self::TEST;
}
}
class TwoSelf extends OneSelf
{
const TEST = "test2";
}
class OneThis extends AOne
{
public function test()
{
return $this::TEST;
}
}
class TwoThis extends OneThis
{
const TEST = "test2";
}
$objects = array(
'one, static::' => new OneStatic(),
'two, static::' => new TwoStatic(),
'one, self::' => new OneSelf(),
'two, self::' => new TwoSelf(),
'one, $this::' => new OneThis(),
'two, $this::' => new TwoThis(),
);
$results = array();
foreach ($objects as $name=>$object)
$results[$name] = $object->test();
var_dump($results);
?>
哪个收益率
>’one,static ::’=> ‘TEST1’
>’two,static ::’=> ‘TEST2’
>’one,self ::’=> ‘TEST1’
>’two,self ::’=> ‘TEST1’
>’one,$this ::’=> ‘TEST1’
>’two,$this ::’=> ‘TEST2’
所以self指的是定义方法的类,但在这些非静态方法中$this ::和static ::之间没有区别.