Jump to content

Class variables are all being set to the last variable


spelltwister

Recommended Posts

Hey all,

I was attempting to play around with classes,  figuring out the proper syntax and such and I ran into a very annoying problem.  Hopefully someone can point out what i'm doing wrong.  I'm using PHP5.  The problem is that all variables assume the value of the last assignment that I made.

Here's one attempt:

<?php

class ship{
  public $gen=0;
  public $infantry=0;
  public $type;
 
  public function setGen($g){
    $this->$gen = $g;
  }
  public function setInf($i){
    $this->$infantry = $i;
  }
  public function getGen(){
    echo $this->$gen;
  }
  public function getInf(){
    echo $this->$infantry;
  }
}

define("MM", 1);
define("FRI", 2);
define("SOL", 3);

$ship = new ship();
$ship->setGen(0);
$ship->setInf(1);
$ship->getGen();//outputs 1, should be 0
$ship->getInf();//outputs 1

?>

Here's another attempt:

class ship{
  public $gen=0;
  public $infantry=0;
  public $type;
 
  public function __construct($g, $i, $t){
    $this->$gen = $g;
echo $this->$gen;//correct
$this->$infantry = $i;
echo $this->$gen;//value of $i
echo $this->$infantry;//correct
$this->$type = $t;
echo $this->$gen;//value of $t
echo $this->$infantry;//value of $t
  }
 
  public function getGen(){
    echo $this->$gen;//value of $t
  }
  public function getInf(){
    echo $this->$infantry;//value of $t
  }
}

define("MM", 1);
define("FRI", 2);
define("SOL", 3);

$ship = new ship(0,2,MM);
echo $ship->$type;//correct

$ships = array();
for($i=1;$i<10;$i++){
  echo "\n".$i;
  $ships[$i] = new ship($i, 0, FRI);
}

for($i=1;$i<10;$i++){
  echo "\n".$i;
  $ships[$i]->getInf();
  $ships[$i]->getGen();
}
?>

Thanks,

Mike

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.