开发者

__set and Property Overloading

开发者 https://www.devze.com 2023-01-30 16:57 出处:网络
class object { public function __construct() {} public function __set($property, $value) { $this->$property = $value;
class object
{
    public function __construct() {}

    public function __set($property, $value) 
    { 
         $this->$property = $value;
    }

    public function __get($property) 
    {
        if (isset($property))
            return $this->$property;
    }
}

I get the concept of Property Overloading now. But I'm not entirely sure why the code have double $'s.

For example this statement: $this->$property = $value; versus the usual $this->property = $value;

My guess is that the reason why both statement are different is:

The $this->property = $value statement is use when the class have explicitly defined property. To clarified, code with a property that is explicitly defined: class object { private $property; __construct(){} /... setter, getter/ }

Where as $this->$property = $value; is used for dynamically created property. So $this->$property is actually referring to the _set's $property argument. For clarity: _set($property,$value), the first __set method's argument (bolded).

Heck, maybe the code is just creating a new variable named $property, instead of referring to the 1st argument in the __set, and $this-> is just for开发者_如何学编程cing the class to acknowledge that the class have a new property...


Your understanding is right. This is one use of variable variables; in this specific case, variable class properties.

PHP parses $this->$property as $this->{string value of $property}, and returns the property of your object that named whatever $property is set to.

Your __get() implementation is slightly off though, you forgot $this->:

        if (isset($this->$property))
            return $this->$property;


It's a variable variable

public function __set($property, $value) 
{ 
     $this->$property = $value;
}

So when you do $this->foo = 'bar' PHP will notice the there is no accessible property foo available and delegate to the __set method with 'foo' for $property and 'bar' for $value. This, in turn, is evaluated to the following expression:

$this->foo = 'bar';

On a sidenote, __get and __set are not a replacement for proper getters and setters. They are much more related to error handling. They are also much slower than using regular functions and they also make your API harder to read.


If $property="myVar" , by using $this->$property you are actually refering to $this->myVar .. it's kinda like $var1='test'; $test=10; echo $$var1; returns 10 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号