renaming a variable name in php at runtime
I am trying to convert an xml document into an associative array.
I want the name of the array to be the root node in the xml document.
I get this information by $xml->getName()
.
I thought of creating an em开发者_如何学Cpty array using this statement, but it does not work.
$($xml->getName()) = array();
Other way should be creating a temp variable and renaming it with $xml->getName()
. Is there a way I can do this in PHP?
You can create it this way:
${$xml->getName()} = array();
You may also wish to validate the name to ensure it meets PHP variable name standards to avoid a runtime error.
George is right, ${$xml->getName()} = array();
will allow you to do basically what you're asking for.
As lonesomeday suggested, this is a bad idea. You're best off wrapping all of that functionality in a function and simply returning it to some greater context. If you're not comfortable, make it a key in an array. Here's the problem though:
- You can't abstract this functionality -- imagine that you want this to be a part of a function or a class (which you should be thinking of anyway), how would you have the class/context of the calling function know that $root is now a reference to your XML?
- You can't load more than one file in a script, if you have two files which start with
<root>
, they will kill each other (this will even prevent use of array keys). - This will lead to debug issues. At a bare minimum, you will need to make sure that there are no issues in the XML syntax as well as the PHP syntax. That leads to increased time in debug & maintenance cycles and therefore technical bloat.
- Definitionally, it is destructive and unexpected behavior -- it effects its environment in ways which are not immediately apparent to the next programmer and it has the potential to unset variables which some other programmer has set.
精彩评论