PHP字符串:如何使用花括号来解析函数返回的对象

时间:2013-09-01 23:38:39

标签: php string parsing

我有一个返回对象的函数。如何编写一个解析该函数​​返回的对象成员的字符串(该函数位于不同的命名空间中)? 这就是我要做的,但 echo 上使用的字符串无效。

namespace security;
function &get_user() {
    $user = (object) array('email' => 'abcd@abcd.com', 'name' => 'John Doe');
    return $user;
}

echo "<li><p class=\"navbar-text\">Welcome, {${\security\get_user()}->name}</p></li>";

2 个答案:

答案 0 :(得分:3)

嗯,有一些事情:

  • 你不能在字符串里面interpolate函数/方法。只允许变量。
  • 创建namespace时,只需在命名空间之外引用它。
  • 除非您了解他们的行为,否则请勿使用references&)。在PHP中,引用的工作方式与大多数其他语言不同。

这就是代码的样子。

// We define the namespace here. We do not need
// to refer to it when inside the namespace.
namespace security;

// Objects and arrays are always passed by
// reference, so you should not use & here
function get_user() {
    return (object) array(
        'email' => 'abcd@abcd.com',
        'name' => 'John Doe',
    );
}
// We need to get the value from the function
// before interpolating it in the string
$user = get_user();

// There are a few ways to interpolate in PHP
// This is for historical and functional reasons
// Interpolating array items is, "{$arr['key']}"
echo "<li><p class=\"navbar-text\">Welcome, $user->name</p></li>";
echo "<li><p class=\"navbar-text\">Welcome, {$user->name}</p></li>";

答案 1 :(得分:0)

除了访问字符串中的对象成员之外,您不应该做更复杂的事情;它很难阅读并且难以维护(例如,您的IDE在进行重构时可能会错过它)。那说,只是为了它的乐趣:

function get_user() {
    $user = (object) array('email' => 'abcd@abcd.com', 'name' => 'John Doe');
    return $user;
}

echo "<li><p class=\"navbar-text\">Welcome, {${($x = \security\get_user()->name) ? 'x' : 'x'}}</p></li>";

这里需要变量赋值 - 你可以使用函数和字符串中花括号内的任何其他东西,但它们的结果将被解释为变量名。基本上,$str = "{${<some code>}}";相当于$name = eval("<some code>"); $str = $$name;"