问答详情
源自:4-1 对象继承-PHP面向对象编程

什么时候该用$this

<?php
class Human{
    public $name;
    public $height;
    public $age;
    public function eat($food){
        echo $this->name."'s eating ".$food."\n";
    }
}
class NbaPlayer extends Human {
    
    function __construct($name){
        $this->name = $name;
    }
}
$jordan = new NbaPlayer("Jordan");

echo $this->name."\n";//这里用this为什么不行
$this->eat("apple");//这里用this为什么不行


提问者:aiwei笑 2016-01-06 14:26

个回答

  • 张的高
    2016-01-28 21:31:40

    $this的应用场景是类内部

    在外部是不能调用$this

    另外,$this一出现就说明这个类要使用自己的属性或者方法了

  • 回得好请给我好评
    2016-01-07 17:51:23

    $this 你记住是自己的意思。 但是你首先要出现在这里才能叫自己阿。 就好像你从来没有去过一个地方, 你却要去那里找你落下的东西,肯定没有啊。

  • 棒打耗子
    2016-01-06 20:30:40

    this是指针,你要让php解释器知道this到底指的哪一个对象才行,你下面的this指的是上面那么多对象的哪一个呢,function里面的this就很清楚了,唯一一个对象

  • 努力提升
    2016-01-06 19:33:15

    因为在类的外面使用$this来代表某对象,PHP无法知道你要代表哪个对象.