S Shane
S Shane

Reputation: 47

problem with Incrementation in class in PHP

I am learning PHP, I have two classes and I want every time I instantiate a class and call the "getNbVehicules ()" method to show the number of created instances. The problem is, it doesn't seem to work correctly, because there is only "1" appearing when I call the method. Help me please.

<?php
class Vehicule{
    private $marque;
    private $couleur;
    private $annee;
    private $nbVehicules;
    
    public function __construct($uneMarque,  $uneCouleur,  $uneAnnee){
        $this->marque=$uneMarque;
        $this->couleur=$uneCouleur;
        $this->annee=$uneAnnee;
        $this->nbVehicules=0;
    }
    
    public function getMarque(){
        return $this->marque;
    }
    
    public function getCouleur(){
        return $this->couleur;
    }
    
    public function getAnnee(){
        return $this->annee;
    }
    
    public function getNbVehicules(){
        return $this->nbVehicules+=1;
    }
    public function __toString(){
        $message = "";
        $message.= "Marque du vehicule: ".$this->marque." / Couleur du vehicule: ".$this->couleur." / Annee du vehicule: ".$this->annee;
        return $message;
    }
}

class Voiture extends Vehicule{
    private $proprio;
    
    function __construct($uneMarque,  $uneCouleur,  $uneAnnee, $unProprio){
        parent::__construct($uneMarque,  $uneCouleur,  $uneAnnee);
        $this->proprio=$unProprio;
    }
    
    function getProprio(){
        return $this->proprio;
    }

}
$vehicule1 = new Vehicule("Nissan", "Bleu", 2021);
echo "<p> Vehicule [".$vehicule1->getNbVehicules()."]</p>";
echo $vehicule1->__toString();
//
$vehicule2 = new Voiture("Honda", "Rouge", 2020, "Jean");
echo "<p> Vehicule [".$vehicule2->getNbVehicules()."]</p>";
echo $vehicule2->__toString();
echo " / Proprietaire: ".$vehicule2->getProprio();

?>

Upvotes: 0

Views: 58

Answers (1)

David
David

Reputation: 218837

Each Vehicule has its own $nbVehicules value, which is set to 0 and never modified. So basically getNbVehicules() is hard-coded to always return 1.

First, make the value static so there's a single count not associated with any particular instance of Vehicule, and initialize it to 0:

private static $nbVehicules = 0;

Then, since you want it to count the number of created instances, increment it in the constructor, not any time you read it:

public function __construct($uneMarque,  $uneCouleur,  $uneAnnee){
    $this->marque=$uneMarque;
    $this->couleur=$uneCouleur;
    $this->annee=$uneAnnee;

    self::$my_static += 1;
}

Then have a static method to read the value:

public static function getNbVehicules(){
    return self::nbVehicules;
}

Reading the value would be a static operation, not associated with any given instance:

echo "<p> Vehicule [".Vehicule::getNbVehicules()."]</p>";

Upvotes: 3

Related Questions