PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
class X
{
private $m1;
private $m2 = 98;
public function __construct($m1)
{
$this->m1 = $m1;
}
public function __get($nm)
{
if (isset($this->$nm))
return $this->$nm;
else
trigger_error("Notice: Undefined property: X::$nm in xxx.php on line nn", E_NOTICE); # somehow get this done by the interpreter automatically
}
}
$x = new X(56);
echo $x->m3;
How do I get it to throw the error like it normally would do if $this->$nm is not set ? Not by using custom error (E_USER_ERROR) - the default php's error msg.
feyd:~ feyd$ php -r "class foo{function __construct(){$this->notHere;}} new foo();"
PHP Parse error: syntax error, unexpected T_OBJECT_OPERATOR in Command line code on line 1
<span style=color:red>
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in Command line code on line 1
</span>
Assumming I dont have the __get method, I get this error : Notice: Undefined property: X::$m3 in C:\xxx\oop.php on line nn
This is what I what it to fall back to in the else statement of if (isset($this->$nm))
ole wrote:Actually the thing to do anjanesh is not to use __get to access object properties directly under $this but access an array.
Why not? Ok, there's nothing wrong with using an array, in fact it might be better. But how does that solve the original problem?
The only dirty workaround I've found so far is to access the same property again within the __get method. There's code in the zend engine to prevent that from happening.
public function __get($nm)
{
return $this->$nm;
}
public function __set($nm, $value)
{
if (isset($this->$nm))
$this->$nm = $value;
else
return $this->$nm;
}
public function __get($nm)
{
if (!in_array($nm, array('m1', 'm2')))
return $this->nonExistentMember; // Problem is, it would show nonExistentMember not declared rather than value of $nm
return $this->$nm; // If this not set, it would trigger the default E_NOTICE error
}
I would want to do if (!in_array($nm, array('m1', 'm2'))) only because if I had a private member called m4 and dont want that accessed at all outside the class. If dont do this, return $this->$nm would return $this->m4; which is not an error.