Nick99 Posted June 29, 2008 Share Posted June 29, 2008 Hey, is there such a thing as classes/objects in PHP? What I need is like a data structure with a certain set of defined variables, then be able to make several instances of that structue, like "entities" of some sort, say something like this: if (empty($entid)){$entid = 1}structure test{ $var1 = 1 $var2 = 2 $var3 = 3}function makeent($ent){ $ent($entid) //make an instance of test with the name of the variable $entid $entid++;}makeent(test)print($test.var1); So, can someone help me with this? Link to comment Share on other sites More sharing options...
Synook Posted June 29, 2008 Share Posted June 29, 2008 PHP 5 has quite good OO implementation: http://au2.php.net/manual/en/language.oop5.php. class test { public $this->var1 = 1; protected $this->var2 = 2; private $this->var3 = 3; function __construct() { }}$test = new test();print $test->var1; // 1$test->var1++;print $test->var1; // 2print $test->var2; // 2$test->var2++; //Errorprint $test->var3; //Error$test_2 = new test();print $test_2->var1; //1 Link to comment Share on other sites More sharing options...
Nick99 Posted June 29, 2008 Author Share Posted June 29, 2008 Cool, thanks, but one more thing. How would I make the class with the value of a variable?Oh, that won't work because you can't have variable names starting with numbersThis class test { public $this->var1 = 5; public $this->var2 = 0; public $this->hands = "taco"; function __construct {}} gave me Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ',' or ';' in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\battleengine.php on line 5 Link to comment Share on other sites More sharing options...
Synook Posted June 30, 2008 Share Posted June 30, 2008 This...gave meParse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ',' or ';' in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\battleengine.php on line 5Oops sorry you only use the $this reserved variable when calling the test's vars from its methods. E.g.class test { public $var1 = 5; public $var2 = 0; public $hands = "taco"; function __construct {} function showHands() { echo $this->hands; }} Cool, thanks, but one more thing. How would I make the class with the value of a variable?Oh, that won't work because you can't have variable names starting with numbersYou can make instances have any name you want. Indirection can be used too. class test() { public $var1 = 1;}$name = "myTest";$$name = new test();$property = "var1";echo $myTest->$property; //1 Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.