1

I don't know where I am doing wrong. Can somebody show me?

<?php 
    class something
    {
        public $attr1;
        private $attr2;

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

        public function __set($name,$value)
        {
            $this->$name = $value." added something more";
        }
    }

    $a = new something();

    $a->$attr1 = "attr1";
    $a->$attr2 = "attr2";

    echo $a->$attr1; //what I would expect is attr1 as output
    echo $a->$attr2; //what I would expect is attr2 added something more as output
?>
Tarik
  • 79,711
  • 83
  • 236
  • 349
  • Although these 2 magic methods are handy keep in mind many people (me included) do not recommend the usage of these because they [break object encapsulation](http://en.wikipedia.org/wiki/Encapsulation_object-oriented_programming). – Stephane Gosselin May 29 '11 at 21:10
  • 1
    See [this post for a proper usage example](http://stackoverflow.com/questions/3634748/php-zend-say-avoid-magic-methods) that respects encapsulation. – Stephane Gosselin May 29 '11 at 21:17

1 Answers1

6

Remove the multiple instances of $ when accessing the object properties:

$a->$attr1 = "attr1";          $a->attr1 = "attr1";
$a->$attr2 = "attr2";          $a->attr2 = "attr2";

echo $a->$attr1;               echo $a->attr1;
echo $a->$attr2;               echo $a->attr2;
  • Thanks but for some reason, this is the output :`attr1 attr2 added something more added something more`. Why did it add "added something more" twice? – Tarik May 29 '11 at 21:06
  • 1
    @Braveyard: Can you run the code you're trying on [ideone.com](http://ideone.com/) and post the link? The output I'm getting is [`attr1attr2 added something more`](http://ideone.com/ibf9U). –  May 29 '11 at 21:07
  • 1
    @Braveyard: You removed too many instances of `$` (in the `__get` and `__set` functions). Only remove the ones shown in my answer. See [this page for an explanation](http://php.net/manual/en/language.variables.variable.php). –  May 29 '11 at 21:14
  • Well it seems I am doing something different within in the __set function and I am calling `$this->name` instead of `$this->$name` – Tarik May 29 '11 at 21:14