dpbe81245 2014-06-05 04:02
浏览 33
已采纳

变量变量可以用于动态分配类属性,以便允许在PHP中使用变量参数的类构造函数吗?

I am building a class and initially wanted to overload the constructs but discovered this is not allowed in PHP. My solution was using variable arguments for the one constructor. However, I am having some issues using string literals in a key => value pair and assigning the class properties. This leads me to ask my main question - is it actually possible to use variable variables to assign class properties via the constructor?

See example below:

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

}

This seems to correctly assign the values. But then when I do the following:

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

I get an error that the getter method isn't functioning:

Undefined property: funrun::$name

However, when I switch the class code to $this->key, the class property doesn't seem to be assigned at all. When I do $fun_example->$run_id, nothing is returned.

What am I missing here? Is there anyway to use an array with string literals to assign class properties? If not, what is a good way to tackle the variable argument issue with constructors?

  • 写回答

1条回答 默认 最新

  • douquan1015 2014-06-05 04:12
    关注

    $this->name is looking for a property named name. Variable properties are written as:

    $this->$name
    

    See the paragraph beginning with Class properties may also be accessed using variable property names. in the PHP documentation on variable variables

    Your constructor is incorrectly written. It's iterating over the argument list, expecting it to be an associative array. But you're passing the settings as a single argument. So it should be:

    function __construct($args) {
        foreach ($args as $key => $value) {
            $this->$key = $value;
        }
        $this->date = time();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址