0

I currently have the following __get/__set methods in the PHP class example:

class example{

    /*Member variables*/
    protected $a; 
    protected $b = array(); 

    public function __get($name){
        return $this->$name;
    }

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

}

However, in addition to setting standard protected variables, I would also like to be able to set protected arrays within the class. I've looked through some other questions and found general suggestions as to how to simple set variables using the __get/__set methods, but nothing that would allow one to use these magic methods to set BOTH arrays and nonarrays, i.e. in the following manner:

$fun = new $example(); 
$fun->a = 'yay'; 
$fun->b['coolio'] = 'yay2'; 
0

1 Answer 1

6

Simple, define __get() like so:

public function &__get($name)
{
    return $this->$name;
}

// ...

$fun = new example();
$fun->a = 'yay';
$fun->b['coolio'] = 'yay2';
var_dump($fun);

Output:

object(example)#1 (2) {
  ["a":protected]=>
  string(3) "yay"
  ["b":protected]=>
  array(1) {
    ["coolio"]=>
    string(4) "yay2"
  }
}

Do take necessary care when you're dealing with references, it's easy to mess up and introduce hard to track bugs.

Sign up to request clarification or add additional context in comments.

7 Comments

Impressive, if that's really possible x) But I have to say, how is this not documented? PHP magic methods
This is documented briefly but I wanted to delve a bit further. If get is being set by reference, will the set function remain identical to before? Additionally, given the risk of bugs with a get function that involves references, would you suggest that I simply create a different set of functions to deal with arrays?
__set() is only called when the property as a whole is being assigned a value, i.e. $fun->b = something_else;
Even after all these years, I just.cant.believe that returning by ref does not actually enable modification of the protected variable through that ref if the ref is assigned to a variable (you 'd need $a = &$fun->foo to enable that). Well played, PHP, well played. Am I missing something or is this a) completely unreasonable, b) par for the course, and c) reason enough to always make __get return by ref?
@Jon Apparently, according to this 3v4l it's supposed to work this way ... I'm a ... surprised a little myself :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.