Tarik
Tarik

Reputation: 81721

Problem with __get and __set code

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
?>

Upvotes: 1

Views: 135

Answers (1)

user142162
user142162

Reputation:

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;

Upvotes: 6

Related Questions