duanguan1573 2012-05-14 12:02
浏览 9
已采纳

PHP通过var名称设置数据

I have class

class User extends BaseModel{
     public $id;
     public $name;
}

class BaseModel{
     function __construct($data=null){
          if($data!=null)
          //set $id and $name
     }
}

I would like to set $id , $name and any other data that extends BaseModel by calling

$test = new User(array('id'=>1,'name'=>'user name'))

I tried to use

$this->__set($arrayKey,$arrayValue);

But i got error : Fatal error: Call to undefined method User::__set() What am I doing wrong? Thank you for any help.

  • 写回答

3条回答 默认 最新

  • doyp9057 2012-05-14 12:12
    关注

    Just loop through the data and assign each property:

    class BaseModel {
         function __construct($data = NULL) {
              foreach ((array) $data as $k => $v) {
                  $this->$k = $v;
              }
         }
    }
    

    The reason you got the error about __set() not being defined is because you didn't define it. Although __set() is a magic method, you do still have to define it's behavior if you want to do something with it.

    http://www.php.net/manual/en/language.oop5.overloading.php#object.set

    __set is run when writing data to inaccessible properties

    This means if you try to "set" a class variable in a scope you're not allowed to (like a private or protected variable), this function will run.

    class Test {
        private $var;
    }
    
    $c = new Test;
    $c->var = 1; // Error, or call __set if defined
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害