I have a User class extending an Id abstract class. Somehow I will introduce another class called Event extending the Id class too. The __construct() methods are very similar, so I want to put the constructor code in the Id class.
Here is my __construct() method:
class Event extends Id
{
public function __construct($id, $object){
$this->id = $id;
foreach($object as $property => $value) {
if (property_exists($this, $property)) $this->$property = $value;
}
}
}
class User extends Id
{
public function __construct($id, $object){
$this->id = $id;
foreach($object as $property => $value) {
if (property_exists($this, $property)) $this->$property = $value;
}
}
}
However, if I put the method in the Id class, PHP warns me at $this->$property = $value;. It says that I have some attributes stated private in the User or Event class so that it cannot be initiated in Id class.
What I want is to reuse my code while keeping those variables private (because I do not want other except parent class to access them!)
Some options:
Use
protectedvariablesYou could use Reflection to cheat and set private variables.
Use traits (5.4) to import a common
__constructRefactor a bit. e.g., have a
setPropertyin the child classes that the parent calls, or implement__set, etc