是否可以使用可变变量来动态赋值类属性,从而允许PHP中的类构造函数具有可变参数?


Can variable variables be used to dynamically assign class properties, so as to allow class constructors with variable arguments in PHP?

我正在构建一个类,最初想重载这些结构,但发现这在PHP中是不允许的。我的解决方案是为一个构造函数使用可变参数。但是,我在键=>值对中使用字符串文字并分配类属性时遇到了一些问题。这导致我问我的主要问题-它实际上是可能的使用变量变量分配类属性通过构造函数?

请看下面的例子:

class funrun{
   protected $run_id; 
   protected $fun_id; 
   protected $funrun_title; 
   protected $date; 
   function __construct(){
     if (func_num_args() > 0){
       $args = func_get_args(0); 
       foreach($args as $key => $value){
          $this->$key = $value;
       }
     $this->date = date();
     function __get($name){
        return $this->name; 
     }
     function __set($name,$value){
         $this->name = $value; 
     } 
}

这似乎正确地赋值。但是当我执行以下操作时:

$settings = array ('run_id' => 5, 'fun_id' => 3); 
$fun_example = new funrun($settings); 
echo $fun_example->run_id; 

我得到一个错误,getter方法不起作用:

Undefined property: funrun::$name

然而,当我将类代码切换到$this->key时,类属性似乎根本没有被分配。当我做$fun_example->$run_id时,什么也不返回。

我在这里错过了什么?是否有任何方式使用字符串字面量的数组来分配类属性?如果不是,那么用构造函数解决变量参数问题的好方法是什么?

$this->name正在查找名为name的属性。变量属性写成:

$this->$name

参见以开头的段落。类属性也可以使用变量属性名访问。中关于变量的PHP文档

构造函数写错了。它在参数列表上迭代,期望它是一个关联数组。但是你把设置作为一个参数传递。所以应该是:

function __construct($args) {
    foreach ($args as $key => $value) {
        $this->$key = $value;
    }
    $this->date = time();
}