doupixian1436 2010-12-06 10:46
浏览 28
已采纳

OOP PHP:我如何分配变量值?

Not very good at putting this question into words....

I'm using an API to update some customer information

$customer =             new Customer();
$customer->first_name = $value;
$customer->update();

The above would update the first_name, however I'd like to variable where first name is like:

$attribute =                'first_name';    
$customer =                 new Customer();
$customer->$attribute =     $value;
$customer->update();`

Which would then reference the public vars in the Customer class.

I want to avoid writing a method(setter) for every attribute.

  • 写回答

2条回答 默认 最新

  • dongtun4268 2010-12-06 10:54
    关注

    Both $obj->$attr and $obj->{$attr} will work in the same way. The {} are redundant in this case. They make sense when you need to write something like $obj->{"123"}.

    <?php
    $obj = new stdClass();
    $attr = 'my_attr';
    $obj->$attr = 'test'; 
    var_dump($obj);
    ?>
    

    The problem with your code is that you have a typo. Or if the typo was only in the text of question, then you don't have any problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'