PHP类中的$this和self的区别

$this代表当前对象(类)的实例,self代表当前类,当前类的实例很好理解,那么什么叫当前类呢? 看看下面例子:

<?php
class Person {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }

    public function getTitle() {
        return $this->getName()." the person";
    }

    public function sayHello() {
        echo "Hello, I'm ".$this->getTitle()."<br/>";
    }

    public function sayGoodbye() {
        echo "Goodbye from ".self::getTitle()."<br/>";
    }
}

class Geek extends Person {
    public function __construct($name) {
        parent::__construct($name);
    }

    public function getTitle() {
        return $this->getName()." the geek";
    }
}

$geekObj = new Geek("Ludwig");
$geekObj->sayHello();
$geekObj->sayGoodbye();

上面代码将会输出:

Hello, I'm Ludwig the geek
Goodbye from Ludwig the person

子类覆盖了父类的方法之后,在外面我们是无法访问父类被覆盖的方法,那么在子类中和在父类中是可以访问的:

  • 在子类中可以通过parent::method()访问
  • 在父类中可以通过self::method()访问