spelltwister Posted December 31, 2006 Share Posted December 31, 2006 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:<?phpclass 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 Link to comment https://forums.phpfreaks.com/topic/32411-class-variables-are-all-being-set-to-the-last-variable/ Share on other sites More sharing options...
dcro2 Posted December 31, 2006 Share Posted December 31, 2006 Variables in classes are accessed without the $, like:[code]$this->infantry = $g;[/code]not[code]$this->$infantry = $g;[/code] Link to comment https://forums.phpfreaks.com/topic/32411-class-variables-are-all-being-set-to-the-last-variable/#findComment-150530 Share on other sites More sharing options...
spelltwister Posted December 31, 2006 Author Share Posted December 31, 2006 omg, thank you so much. Link to comment https://forums.phpfreaks.com/topic/32411-class-variables-are-all-being-set-to-the-last-variable/#findComment-150531 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.