Possible Duplicate:
PHP __get and __set magic methods
Just starting with OOP. . Anyway not sure if I understand it correctly but shouldn’t the code not change the value of $attribute, because of function __set()?
<?php
class aclass
{
protected $attribute; //edited from public to protected
public function __get ($name)
{
return $this->$name;
}
public function __set ($name, $value)
{
if($name == "foo")
{
$this->$name = $value;
}
}
}
$a = new aclass();
$a->attribute = "bar";
echo $a->attribute;
?>
When I run this an error message shows:
“Fatal error: Cannot access protected property aclass::$attribute . . . on line 16”
Line 16 is “echo $a->attribute” – Other posts say that the attribute must be set to PROTECTED but its not working. Im using PHP 5.4.3 – Any ideas?
Your
__set()magic method will be invoked only when trying to access non-public or undefined properties, but theattributeproperty IS defined and IS public, so it is accessed directly.If you want the
__set()method to “intecept” accesses toattribute, it must be madeprotectedorprivate.