Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP trying to create dynamic variables in classes

I need to construct a class with alot of variables directly from the Database, For simplicity we'll name them 'userX', I've looked into ORM just a little, but its way over my head.

Essentially I thought I could use my procedural code

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

But, in a class

class test() {

  private $var1;

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

  function __constructor .....

}

Obviously not.. but it leaves me with the same problem, how can I add $user0, $user1, $user2, etc etc, without having to type all 10k of them in..

Obviously, it would be 1000x easier to just grab the names from the Database, but again, that looks even harder to code. Should I buckle down and grab them all ORM style?

like image 421
BaneStar007 Avatar asked Dec 01 '22 23:12

BaneStar007


2 Answers

You could simply use the magic accessors to have as many instance attributes as you wish :

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 could use your instance like this :

$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 to add a lot of attributes :

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

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

//$values is an associative array 
public function __construct($values){
    $this->data = $values;
}
like image 55
ibtarek Avatar answered Dec 04 '22 02:12

ibtarek


Try $this->{$varname}

class test
{

    function __construct(){

       for($i=0;$i<100;$i++)
       {

         $varname='var'.$i;
         $this->{$varname}=$i;
       }
    }
}
like image 28
RafaSashi Avatar answered Dec 04 '22 04:12

RafaSashi