When to use self over $this?

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

    I believe question was not whether you can call the static member of the class by calling ClassName::staticMember. Question was what's the difference between using self::classmember and $this->classmember.

    For e.g., both of the following examples work without any errors, whether you use self:: or $this->

    class Person{
        private $name;
        private $address;
    
        public function __construct($new_name,$new_address){
            $this->name = $new_name;
            $this->address = $new_address;
        }
    }
    
    class Person{
        private $name;
        private $address;
        public function __construct($new_name,$new_address){
            self::$name = $new_name;
            self::$address = $new_address;
        }
    }
    

提交回复
热议问题