php this和static,php – static ::和this ::之间的区别::

我知道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 ::之间没有区别.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值