php中$this在普通方法和static方法下的差别

最近在做ECMall的二次开发时,留意到ECMall的启动方法的调用方式为

ECMall::startup

而startup并不是类ECMall的静态方法,为什么可以这样使用呢?在这种调用方式下,类的成员$this又会指代什么呢?我们来做个测试:

<?php

class FirstClass {
    public function output() {
        if (isset($this)) {
            echo '$this is defined (' . get_class($this) . ").\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class SecondClass {
    public function output() {
        FirstClass::output();
    }
}


$firstClass = new FirstClass();
$firstClass->output();
$firstClass::output();
FirstClass::output();

$secondClass = new SecondClass();
$secondClass->output();
$secondClass::output();
SecondClass::output();

?> 

输出结果如下:

$this is defined (FirstClass).
$this is not defined.
$this is not defined.
$this is defined (SecondClass).
$this is not defined.
$this is not defined.

这里要留意到一个细节:在通过SecondClass类调用其成员方法output时,$this是undefined的,当使用SecondClass类的对象调用output方法时,FirstClass中的$this指向了SecondClass的对象。

虽然php的成员方法和Java或C++中的静态方法非常像,但当我们为FirstClass的output方法增加static修饰时,输出又有所不同:

$this is not defined.
$this is not defined.
$this is not defined.
$this is not defined.
$this is not defined.
$this is not defined.

不难看出,如果将FirstClass的output定义为static时,无论通过何种方式,在output中的$this都是undefined。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值