10

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

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?

  • 1
    PHP Version 5.3.4 after executing your code $obj: object(stdClass)#1 (1) { ["b"]=> int(10) } – Fivell Sep 05 '11 at 15:55
  • 2
    It's not a reference. See [this answer](http://stackoverflow.com/questions/3611986/in-php-can-someone-explain-cloning-vs-pointer-reference/3612129#3612129) for details on PHP handles writing variables and references... – ircmaxell Sep 05 '11 at 16:03

3 Answers3

9

Your code works correctly, $obj->b is 10 after execution: http://codepad.org/QnXvueic

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.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
2
<?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
var_dump($obj->b); //10 Works fine
RiaD
  • 46,822
  • 11
  • 79
  • 123
  • That's not a rename, it's a copy. It will occupy twice the memory of ->a. Just saying as "renaming" is often only something important to developers who handle large datasets. – John Oct 03 '17 at 01:57
-1

Use object clonning, Reference : PHP __clone() documentation

Pawan Choudhary
  • 1,073
  • 1
  • 10
  • 20