When to use self over $this?

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

    self (not $self) refers to the type of class, where as $this refers to the current instance of the class. self is for use in static member functions to allow you to access static member variables. $this is used in non-static member functions, and is a reference to the instance of the class on which the member function was called.

    Because this is an object, you use it like: $this->member

    Because self is not an object, it's basically a type that automatically refers to the current class, you use it like: self::member

提交回复
热议问题