When to use self over $this?

前端 未结 23 2807
醉梦人生
醉梦人生 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:11

    In PHP, you use the self keyword to access static properties and methods.

    The problem is that you can replace $this->method() with self::method()anywhere, regardless if method() is declared static or not. So which one should you use?

    Consider this code:

    class ParentClass {
        function test() {
            self::who();    // will output 'parent'
            $this->who();   // will output 'child'
        }
    
        function who() {
            echo 'parent';
        }
    }
    
    class ChildClass extends ParentClass {
        function who() {
            echo 'child';
        }
    }
    
    $obj = new ChildClass();
    $obj->test();
    

    In this example, self::who() will always output ‘parent’, while $this->who() will depend on what class the object has.

    Now we can see that self refers to the class in which it is called, while $this refers to the class of the current object.

    So, you should use self only when $this is not available, or when you don’t want to allow descendant classes to overwrite the current method.

提交回复
热议问题