【问题标题】:Modify PHP Object Property Name修改 PHP 对象属性名称
【发布时间】:2011-08-31 18:17:32
【问题描述】:

在 PHP 中是否可以更改对象属性键/名称?例如:

stdClass Object
(
     [cpus] => 2
     [created_at] => 2011-05-23T01:28:29-07:00
     [memory] => 256
)

我希望将 Object 中的键 created_at 更改为 created,留下一个看起来像这样的对象:

stdClass Object
(
     [cpus] => 2
     [created] => 2011-05-23T01:28:29-07:00
     [memory] => 256
)

【问题讨论】:

    标签: php object properties


    【解决方案1】:
    $object->created = $object->created_at;
    unset($object->created_at);
    

    不过,适配器类之类的东西可能是更可靠的选择,具体取决于需要此操作的位置和频率。

    class PC {
        public $cpus;
        public $created;
        public $memory;
    
        public function __construct($obj) {
            $this->cpus    = $obj->cpu;
            $this->created = $obj->created_at;
            $this->memory  = $obj->memory;
        }
    }
    
    $object = new PC($object);
    

    【讨论】:

      【解决方案2】:

      不,因为键是对值的引用,而不是值本身。 最好先复制原件,然后将其删除。

      $obj->created = $obj->created_at;
      unset(obj->created_at);
      

      【讨论】:

      • “否”实际上应该是“是”!你给出了错误的答案,但提供了正确的解决方案。
      【解决方案3】:

      它类似于@deceze 适配器,但不需要创建额外的类

      $object = (object) array(
        'cpus'    => $obj->cpus,
        'created' => $obj->created_at,
        'memory'  => $obj->memory
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2021-08-28
        • 1970-01-01
        • 1970-01-01
        • 2013-04-18
        • 1970-01-01
        相关资源
        最近更新 更多