mythicalprogrammer
mythicalprogrammer

Reputation: 4737

__set and Property Overloading

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 forcing the class to acknowledge that the class have a new property...

Upvotes: 0

Views: 567

Answers (3)

Catalin
Catalin

Reputation: 868

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 :)

Upvotes: 1

BoltClock
BoltClock

Reputation: 723598

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;

Upvotes: 2

Gordon
Gordon

Reputation: 316969

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.

Upvotes: 2

Related Questions