PHP is trying to create dynamic variables in classes

I need to build a class with many variables directly from the database. For simplicity, we will call them "userX", I studied ORM a bit, but on my way.

Essentially, I thought I could use my procedural code

for ($i=0; $i<100; $i++) { public ${'user'.$i}; } 

But in the classroom

 class test() { private $var1; for ($i=0; $i<10000; $i++) { public ${'user'.$i}; } function __constructor ..... } 

Obviously not .. but this leaves me with the same problem as I can add $ user0, $ user1, $ user2 etc. etc. without typing them in 10k.

Obviously, it would be easier to just grab the names from the database, but, again, this looks even more difficult for the code. Should I buckle up and grab their entire ORM style?

+4
source share
3 answers

You can simply use magic accessors to have as many instance attributes as you like:

 class test{ private $data; public function __get($varName){ if (!array_key_exists($varName,$this->data)){ //this attribute is not defined! throw new Exception('.....'); } else return $this->data[$varName]; } public function __set($varName,$value){ $this->data[$varName] = $value; } } 

Then you can use your instance as follows:

 $t = new test(); $t->var1 = 'value'; $t->foo = 1; $t->bar = 555; //this should throw an exception as "someVarname" is not defined $t->someVarname; 

And add a lot of attributes:

 for ($i=0;$i<100;$i++) $t->{'var'.$i} = 'somevalue'; 

You can also initialize a newly created instance with a given set of attributes.

 //$values is an associative array public function __construct($values){ $this->data = $values; } 
+14
source

Try $ this → {$ varname}

 class test { function __construct(){ for($i=0;$i<100;$i++) { $varname='var'.$i; $this->{$varname}=$i; } } } 
+1
source

You can use variable variables ($$ var) - the contents of one variable is used as the name for another variable (double $$)

Therefore, not $ this-> varname, but $ this → $ varname .

 class test { for($i=0;$i<100;$i++) { $varname='var'.$i; $this->$varname=$i; } } 

This will dynamically create 100 variables with the names $ var0, $ var1 ...

-1
source

Source: https://habr.com/ru/post/1433126/


All Articles