在PHP5中,使用self和$this有什么区别?

什么时候合适?


当前回答

当self与::运算符一起使用时,它引用当前类,这可以在静态和非静态上下文中完成$这是指对象本身。此外,使用$this调用静态方法(但不引用字段)是完全合法的。

其他回答

self是指当前类(在其中调用它),

$这是指当前对象。您可以使用static而不是self。

请参见示例:

class ParentClass {
    function test() {
        self::which();    // Outputs 'parent'
        $this->which();   // Outputs 'child'
    }

    function which() {
        echo 'parent';
    }
}

class ChildClass extends ParentClass {
    function which() {
        echo 'child';
    }
}

$obj = new ChildClass();
$obj->test();

输出:

 parent
 child

根据php.net,这里有三个特殊的关键字:self、parent和static。它们用于从类定义内部访问财产或方法。

另一方面,$this用于调用任何类的实例和方法,只要该类是可访问的。

关键字self不仅仅指“当前类”,至少不会限制静态成员。在非静态成员的上下文中,self还提供了一种绕过当前对象的vtable(参见vtable上的wiki)的方法。正如您可以使用parent::methodName()调用函数的父版本一样,您也可以调用self::methodName)调用方法的当前类实现。

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();

这将输出:

你好,我是极客路德维希路德维希再见了

sayHello()使用$this指针,因此调用vtable调用Geek::getTitle()。sayGoodbye()使用self::getTitle(),因此不使用vtable,而是调用Person::getTitle()。在这两种情况下,我们都在处理实例化对象的方法,并且可以访问调用函数中的$this指针。

当self与::运算符一起使用时,它引用当前类,这可以在静态和非静态上下文中完成$这是指对象本身。此外,使用$this调用静态方法(但不引用字段)是完全合法的。

self(不是$self)指的是类的类型,而$this指的是该类的当前实例。self用于静态成员函数,允许您访问静态成员变量$这用于非静态成员函数,是对调用成员函数的类实例的引用。

因为这是一个对象,所以可以像这样使用它:$this->member

因为self不是一个对象,所以它基本上是一个自动引用当前类的类型。您可以像:self::member一样使用它