Pass data in php constructor to class

4

I have a question about how to submit data for creating a goal, I read in some tutorials that it was just put this way in PHP4:

$elo1=new Elo(1300);
$elo1->fc_Elo();

But the way I saw it on some web sites, the code is too long, does it have some way like in the middle above for the current PHP version?

This is the original code that is working:

    class Elo{
        public $mmr;

        function fc_Elo(){
            if($this->mmr == 1300){
                echo "Teste".$this->mmr;
            }
            else{
                echo "1".$this->mmr;
            }
        }
    }

    $elo1=new Elo;
    $elo1->mmr = 1300;
    $elo1->fc_Elo();
    
asked by anonymous 18.09.2015 / 03:31

1 answer

4

To pass value in the constructor, use the __construct () method.

class Elo{
   public $name;
   public $sexo;
   public $mmr;

    public function __construct($nome, $sexo){
       $this->name = $nome;
       $this->sexo = $sexo;        
    }

   public function fc_Elo(){
      if($this->mmr == 1300){
         echo "Teste".$this->mmr;
      }else{
         echo "1".$this->mmr;
      }
  }
}

$elo = new Elo('teste', '3x semana');
echo $elo->name .' - '. $elo->sexo;
    
18.09.2015 / 04:04