如何使用字符串访问对象(simpleXML)变量名?

i need to access a simplexml object using a string. ie.

$x->a->b = 'obj'; $s = 'a->b'; echo $x->$s;

but it doesn't seem to work...

please help!

:)

you could use references:

$s =& $x->a->b;

or, if you want the string approach, build up the reference step by step:

function getRef($base, $str) {
    $out = $base;
    $parts = explode("->", $str);

    foreach ($parts as $p) {
        $out = $out->$p;
    }

    return $out;
}

getRef($x, "a->b");

That will not work. Are you trying to use xpath?

http://www.php.net/manual/en/simplexmlelement.xpath.php

You can do that like this, if my memory serves me:

echo $x->{$s};