When to use self over $this?

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

    DO NOT USE self::, use static::

    There is another aspect of self:: that is worth mentioning. Annoyingly self:: refers to the scope at the point of definition not at the point of execution. Consider this simple class with two methods:

    class Person
    {
    
        public static function status()
        {
            self::getStatus();
        }
    
        protected static function getStatus()
        {
            echo "Person is alive";
        }
    
    }
    

    If we call Person::status() we will see "Person is alive" . Now consider what happens when we make a class that inherits from this:

    class Deceased extends Person
    {
    
        protected static function getStatus()
        {
            echo "Person is deceased";
        }
    
    }
    

    Calling Deceased::status() we would expect to see "Person is deceased" however what we see is "Person is alive" as the scope contains the original method definition when call to self::getStatus() was defined.

    PHP 5.3 has a solution. the static:: resolution operator implements "late static binding" which is a fancy way of saying that it's bound to the scope of the class called. Change the line in status() to static::getStatus() and the results are what you would expect. In older versions of PHP you will have to find a kludge to do this.

    See PHP Documentation

    So to answer the question not as asked ...

    $this-> refers to the current object (an instance of a class), whereas static:: refers to a class

提交回复
热议问题