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?

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;
}

Need Your Help

How get the value of multiple checkboxes in javascript

javascript

I used checkbox in two items now I can get the value of the second group of checkbox.

Ogre3D Basic Framework issue on Ubuntu

c++ netbeans ubuntu ogre3d

I have been trying to learn to use Ogre3D and have gotten to the stage where I want to start something more serious than the examples it comes with so I found and copied the Basic Ogre Framework

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.