When to use self over $this?

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

    self refers current class(in which it is called),

    $this refers current object. You can use static instead of self. See the example:

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

    Output: parent child

提交回复
热议问题