PHP试图在类中创建动态变量


PHP trying to create dynamic variables in classes

我需要直接从数据库中构造一个包含大量变量的类,为了简单起见,我们将它们命名为"userX",我只研究了一点ORM,但它超出了我的想象。

本质上,我认为我可以使用我的程序代码

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

但是,在一类中

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

显然不是。。但它给我留下了同样的问题,我如何添加$user0、$user1、$user2等,而不必在中键入所有10k

显然,只从数据库中获取名称会容易1000倍,但同样,这看起来更难编码。我应该系好安全带,把它们都抓起来吗?

您可以简单地使用魔术访问器来拥有任意多的实例属性:

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

然后你可以这样使用你的实例:

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

并添加了许多属性:

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

您还可以使用给定的属性集初始化新创建的实例

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

尝试$this->{$varname}

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

您可以使用变量变量($$var)-一个变量的内容用作其他变量的名称(双$$)

因此,不是$this->varname,而是$this-->$varname

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

这将动态创建100个名称为$var0、$var1。。。