Home > Net >  Magic getter inheritance
Magic getter inheritance

Time:04-19

I’m following this article to try to make each of my PHP classes, inherit from a getter defined in a base class. I would found this very convenient not to rewrite magic getters in each and every class… (maybe it has bad consequencies ? if so, please tell me !) The thing is I have this error : Undefined property: Personne::$nom, and I don’t know why.

Here’s the code :

class classeBase {
    public function __get($propriete) {
        if(property_exists($this,$propriete)) return $this->$propriete; 
        else return null;
    }
}
    
class Personne extends classeBase {
    private $nom;
    private $prenom;
        
    //constructor...
}
    
$p1 = new Personne(array("nom" => "nom1", "prenom" => "prenom1"));  
echo $p1->nom;
echo $p1->prenom;

3 more precisions :

  • The constructor works fine (a var_dump() of the created instance shows nom1 and prenom1 well assigned)
  • I have the same error with the code of the article, when I try to get to each properties of an instance of Example_Object
  • I don’t have any error when the magic getter is defined inside the Personne class

Can somebody explain me what’s going on here ? (maybe what I wan’t to do is impossible)

Thanks !

CodePudding user response:

The problem is that the variables are private. Private variables are only accessible from the same class that declared them, but you're trying to access them from the parent class.

Declare them protected, this allows them to be accessed from any class in the same class hierarchy, either parents or children, but not from outside these classes.

<?php
class classeBase {
    public function __get($propriete) {
        if(property_exists($this,$propriete)) return $this->$propriete;
        else return null;
    }
}

class Personne extends classeBase {
    protected $nom;
    protected $prenom;

    public function __construct($array) {
        foreach ($array as $key => $value) {
            $this->$key = $value;
        }
    }
}

$p1 = new Personne(array("nom" => "nom1", "prenom" => "prenom1"));
echo $p1->nom;
echo $p1->prenom;
  • Related