When to use self over $this?

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

    • The object pointer $this to refers to the current object.
    • The class value static refers to the current object.
    • The class value self refers to the exact class it was defined in.
    • The class value parent refers to the parent of the exact class it was defined in.

    See the following example which shows overloading.

    newThisClass()); // B
    var_dump($b->newParentClass()); // A
    
    
    class C extends B
    {
        public static function newSelfClass()
        {
            return new self;
        }
    }
    
    
    $c = new C;
    
    var_dump($c::newStaticClass()); // C
    var_dump($c::newSelfClass()); // C because self now points to "C" class
    var_dump($c->newThisClass()); // C
    var_dump($b->newParentClass()); // A because parent was defined *way back* in class "B"
    

    Most of the time you want to refer to the current class which is why you use static or $this. However, there are times when you need self because you want the original class regardless of what extends it. (Very, Very seldom)

提交回复
热议问题