Constructeur
Définition : Constructeur
Le constructeur est une méthode "magique" appelée automatiquement lors de la création de l'objet (avec new). Elle s'appelle obligatoirement __construct (avec deux traits de soulignement).
Elle permet d'initialiser l'objet.
1
class Identite {
2
protected $nom;
3
protected $prenom;
4
public function __construct(string $nom, string $prenom)
5
{6
$this->nom = $nom;
7
$this->prenom = $prenom;
8
}
9
public function getNomPrenom(): string {
10
return "{$this->nom()} {$this->prenom()}";
11
}
12
}
13
$fiche = new Identite("vanneste", "vincent");
14
echo $fiche->getNomPrenom();