<?php
abstract class AbstractClass
{
public function __get($theName)
{
return (isset($this->$theName)) ? $this->$theName : NULL;
}
public function __set($theName, $theValue)
{
if (false === property_exists(get_class(), $theName)) {
throw new Exception(get_class()." does not have '".$theName."' property.");
} else {
$this->$theName = $theValue;
}
}
}
class ConcreteClass extends AbstractClass
{
private $x;
private $y;
public function __construct($theX, $theY)
{
$this->x = $theX;
$this->y = $theY;
}
}
$concreteClass = new ConcreteClass(10, 20);
var_dump( $concreteClass->x );
Is there some way to amke this work or will I have to add those magic methods to the extended class?
This would work:
public function __get($theName)
{
if(property_exists($this, $theName)) {
$reflection = new ReflectionProperty($this, $theName);
$reflection->setAccessible($theName);
return $reflection->getValue($this);
}
}
IMO, you shouldn't use __get
and __set
as a replacement for getters and setters. Since they are triggered when trying to access a non-accessible property, they are much more related to error-handling. And they are also much slower than a regular getter or setter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With