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?

2
  • 1
    PHP Version 5.3.4 after executing your code $obj: object(stdClass)#1 (1) { ["b"]=> int(10) } Commented Sep 5, 2011 at 15:55
  • 2
    It's not a reference. See this answer for details on PHP handles writing variables and references... Commented Sep 5, 2011 at 16:03

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's handy. It saves having to do reflection and other fancy stuff like in other languages.
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

1 Comment

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.
-1

Use object clonning, Reference : PHP __clone() documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.