【发布时间】:2014-06-29 12:48:09
【问题描述】:
我知道static:: 和self:: 之间有区别,就像这个例子中一样(来自https://stackoverflow.com/a/13613718/2342518)
<?php
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:: 有什么区别?
可选的完整测试
<?php
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'
- '二,静态::' => 'test2'
- 'one, self::' => 'test1'
- '二,self::' => 'test1'
- '一,$this::' => 'test1'
- '二,$this::' => 'test2'
所以 self 指的是定义方法的类,但是在这些非静态方法中$this:: 和static:: 没有区别。
【问题讨论】:
-
你最后的结论确实是正确的:)