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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)