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

什么时候合适?


当前回答

根据静态关键字,没有任何$self。只有$this用于引用类(对象)的当前实例,self用于引用类的静态成员。对象实例和类之间的区别在这里发挥作用。

其他回答

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

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

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

$this指当前类对象,self指当前类(Not对象)。类是对象的蓝图。所以你定义了一个类,但是你构造了对象。

换句话说,对静态成员或方法使用self,而对非静态成员和方法使用this。

同样在子/父场景中,self/parent主要用于标识子和父类成员和方法。

self::用于当前类的关键字,基本上用于访问静态成员、方法和常量。但是在$this的情况下,不能调用静态成员、方法和函数。

您可以在另一个类中使用self::关键字并访问静态成员、方法和常量。当它将从父类扩展时,在$this关键字的情况下也是如此。当另一个类将从父类扩展时,您可以访问该类中的非静态成员、方法和函数。

下面给出的代码是self::和$this关键字的示例。只需复制并粘贴代码文件中的代码,即可看到输出。

class cars{
    var $doors = 4;
    static $car_wheel = 4;

    public function car_features(){
        echo $this->doors . " Doors <br>";
        echo self::$car_wheel . " Wheels <br>";
    }
}

class spec extends cars{
    function car_spec(){
        print(self::$car_wheel . " Doors <br>");
        print($this->doors . " Wheels <br>");
    }
}

/********Parent class output*********/

$car = new cars;
print_r($car->car_features());

echo "------------------------<br>";

/********Extend class from another class output**********/


$car_spec_show = new spec;

print($car_spec_show->car_spec());

我遇到了同样的问题,简单的答案是:

$这需要类的实例self::不

每当您使用静态方法或静态属性并希望在没有实例化类对象的情况下调用它们时,都需要使用self:来调用它们,因为$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指针。