When to use self over $this?

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

    self:: keyword used for the current class and basically it is used to access static members, methods, and constants. But in case of $this you cannot call the static member, method and functions.

    You can use the self:: keyword in another class and access the static members, method and constants. When it will be extends from parent class and same in case of $this keyword. You can access the non static members, method and function in another class when it will be extends from parent class.

    The code given below is a example of self:: and $this keyword. Just copy and paste the code in your code file and see the output.

    class cars{
        var $doors=4;   
        static $car_wheel=4;
    
      public function car_features(){
        echo $this->doors." Doors 
    "; echo self::$car_wheel." Wheels
    "; } } class spec extends cars{ function car_spec(){ print(self::$car_wheel." Doors
    "); print($this->doors." Wheels
    "); } } /********Parent class output*********/ $car = new cars; print_r($car->car_features()); echo "------------------------
    "; /********Extend class from another class output**********/ $car_spec_show=new spec; print($car_spec_show->car_spec());

提交回复
热议问题