I'm trying to create a base class with common methods to then extend all my classes and avoid repeating methods. At the moment I have a filling method and another for obtaining the properties of the class.
These functions also allow you to manipulate the values before assigning/getting the respective value ( Kind of like Laravel does with accessors and mutators ).
The problem is that it only works when the properties of the child class are public and not private or protected. This is so since in a normal class it cannot be ensured that the property exists in the child class and therefore it cannot generate a dependency.
I have tried with a clase abstracta
, but since I want my properties of the respective classes to be dynamic it is not what I am looking for.
I finally tried with a trait
, but the behavior is the same as with a "normal" class.
Is there an alternative to being able to access the properties of the child classes from the parents?
<?php
class model{
protected $classname;
protected $fillable;
protected $obtainable;
const MUTATOR_FUNCTION_PREFIX = "set_";
const ACCESOR_FUNCTION_PREFIX = "get_";
function __construct(){
$this->fillable = [];
$this->obtainable = [];
}
public function fill($params){
if(gettype($params) != 'array'){
return null;
}
foreach($this->fillable as $property){
$property_exist = isset($params[$property]);
if($property_exist){
$method = self::MUTATOR_FUNCTION_PREFIX . $property;
if(method_exists($this->classname, $method)){
$this->$property = $this->classname::$method($params[$property]);
}else{
$this->$property = $params[$property];
}
}
}
}
public function get(){
$response = new stdClass();
foreach($this->obtainable as $property){
$property_exist = isset($this->$property);
if($property_exist){
$method = self::ACCESOR_FUNCTION_PREFIX . $property;
if(method_exists($this->classname, $method)){
$response->$property = $this->classname::$method($this->$property);
}else{
$response->$property = $this->$property;
}
}
}
return $response;
}
}
class publication extends model {
public $comment;
function __construct(){
$this->fillable = ['comment'];
$this->obtainable = ['comment'];
}
}
$publication = new publication();
$publication->fill(["comment" => "This is my first comment"]);
print_r($publication->get());
In response to:
It is true only in the case that the properties of the "child" class are private (
private
), but if the properties are public (public
) or protected (protected
) then they can be accessed from the "parent" class without any problem.PHP Manual > Classes and objects > Visibility
That is, if we define the property
$comment
of the classpublication
asprotected
, when doingfill()
and/orget()
there should be no problemDemo
In response to:
You can keep your code as is and use
public
orprivate
to define the properties on the child classes