代码之家  ›  专栏  ›  技术社区  ›  significance

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

  •  3
  • significance  · 技术社区  · 16 年前

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

    但似乎不起作用。。。

    :)

    3 回复  |  直到 16 年前
        1
  •  1
  •   nickf    16 年前

    您可以使用参考资料:

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

    或者,如果需要字符串方法,请逐步建立引用:

    function getRef($base, $str) {
        $out = $base;
        $parts = explode("->", $str);
    
        foreach ($parts as $p) {
            $out = $out->$p;
        }
    
        return $out;
    }
    
    getRef($x, "a->b");
    
        2
  •  4
  •   mattbasta    16 年前

    echo $x->{$s};
    
        3
  •  0
  •   ZZ Coder    16 年前

    那是行不通的。您正在尝试使用xpath吗?

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

    推荐文章