PHP - 如何重命名对象属性? [英] PHP - How to rename an object property?
问题描述
我想知道如何在 PHP 中重命名对象属性,例如:
I wonder how can I rename an object property in PHP, e.g.:
<?php
$obj = new stdclass();
$obj->a = 10; // will be renamed
$obj->b = $obj->a; // rename "a" to "b", somehow!
unset($obj->a); // remove the original one
它在 PHP5.3 中不起作用,(不要谈论早期版本)因为将 $obj->a
的引用分配给 $obj->b
等取消设置 $obj->a
,$obj->b
的值将为空.请问有什么想法吗?
It does not work in PHP5.3, (donno about earlier versions) since there will be a reference of $obj->a
assigned to $obj->b
and so by unsetting $obj->a
, the value of $obj->b
will be null. Any ideas please?
推荐答案
你的代码工作正常,$obj->b
执行后为 10
: http://codepad.org/QnXvueic
Your code works correctly, $obj->b
is 10
after execution: http://codepad.org/QnXvueic
当您取消设置 $obj->a
时,您只是删除了该属性,而不会触及该值.如果该值被其他变量使用,则它在 order 变量中保持不变.
When you unset $obj->a
, you just remove the property, you do not touch to the value. If the value is used by an other variable, it's left untouched in the order variable.
这篇关于PHP - 如何重命名对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!