I'm makin a framework to make my own server, to do this i had implemented many classes, one of this is a class named model who is a generic parent class that suports other specific models. this is the construction of the class model:
namespace app\core;
use app\models\RegisterModel;
abstract class Model
{
/*just definition of generic properties and rules to the model*/
public array $errors = [];
public const RULE_REQUIRED = 'required';
public const RULE_EMAIL = 'email';
public const RULE_MIN = 'min';
public const RULE_MAX = 'max';
public const RULE_MATCH = 'match';
/*the purpouse of this function is load data to the object, when i save the data this way it works well*/
public function loadData($data){
foreach($data as $key => $value){
if (property_exists($this, $key)){
$this->{$key} = $value;
}
};
}
/here is the function that is giving troubles to me/
public function validate(){
foreach ($this->rules() as $attibute => $rules) {
// code...
$value = $this->{$attibute};
foreach ($rules as $rule) {
// code...
$ruleName = $rule;
if (!is_string($ruleName)) {
// code...
$ruleName = $rule[0];
}
if ($ruleName == self::RULE_REQUIRED && !$value){
$this->addError($attribute, self::RULE_REQUIRED);
}
}
}
}
this is the child class
namespace app\models;
use app\core\Model;
class RegisterModel extends Model
{
public string $firstname;
public string $lastname;
public string $email;
public string $password;
public string $confirmPassword;
/*los nombres tienen que coincidir con los deldocumento register.php*/
public function register(){
return true;
}
public function rules(): array{
return [
'firstname'=> [self::RULE_REQUIRED],
'lastname'=> [self::RULE_REQUIRED],
'email'=> [self::RULE_REQUIRED, self::RULE_EMAIL],
'password'=> [self::RULE_REQUIRED, [self::RULE_MIN, 'min'=>8], [self::RULE_MAX, 'max'=>24]],
'password'=> [self::RULE_REQUIRED, [self::RULE_MATCH, 'match'=>'password']]
];
}
}
when i create a instance (lets call it ChildInstance) of the class and load the information of $firstname, $lastname, $email, $password, $confirmpasword and then use var_dump on ChildInstance I can see the information i load on this instance. but when i use the function validate (both functions validate and loadData belongs to the parent class) it raise this error:
Uncaught Error: Typed property app\models\RegisterModel::$firstname must not be accessed before initialization
I already solved this problem by using inheritance, but I can't solve it using this aproach, why the information stored cannot be accesed using a function of the parent class? thank you