Pass data in php constructor to class

Asked

Viewed 890 times

4

I have a question of how to send the data to create a goal, I read in some tutorials that was just put this way in PHP4:

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

However the way I saw in some places of the web, it gets very extensive the code, has some way as in the middle above for the current version of PHP?

This is the original code that’s 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();
  • I don’t understand, you wonder if in php5 it is possible to pass argument in the constructor?

  • In php4 to give information to the object and this way: $elo1=new Elo(1300, value2, Valor3); I would like it in a similar way, instead of passing each information in each line, example of the current: $elo1->mmr = 1300; $elo1->valor2 = xxx; $elo1->Valor3 = yyy;

1 answer

4


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

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;
  • My question is on the part of creating the information of objects, not on itself in the class. For example, I have 2 public in class: public $name; public $sex; in case I want to know if you have how instead of writing $elo1=new Elo; $elo1->name = "Alex"; $elo1->sex = "Male"; which looks like the php4 $elo1=new Elo scheme("Alex","Male");

  • @Alexbarros, yes it is possible!

  • can you explain to me how?

  • Just set the parameters in the constructor. or you want them to be variables?

  • variables in this situation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.