When to use self over $this?

前端 未结 23 3185
醉梦人生
醉梦人生 2020-11-21 11:19

In PHP 5, what is the difference between using self and $this?

When is each appropriate?

23条回答
  •  执笔经年
    2020-11-21 12:23

    The keyword self does NOT refer merely to the 'current class', at least not in a way that restricts you to static members. Within the context of a non-static member, self also provides a way of bypassing the vtable (see wiki on vtable) for the current object. Just as you can use parent::methodName() to call the parents version of a function, so you can call self::methodName() to call the current classes implementation of a method.

    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()."
    "; } public function sayGoodbye() { echo "Goodbye from ".self::getTitle()."
    "; } } 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();

    This will output:

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

    sayHello() uses the $this pointer, so the vtable is invoked to call Geek::getTitle(). sayGoodbye() uses self::getTitle(), so the vtable is not used, and Person::getTitle() is called. In both cases, we are dealing with the method of an instantiated object, and have access to the $this pointer within the called functions.

提交回复
热议问题