【问题标题】:How to chain objects of mixed types in PHP5如何在 PHP5 中链接混合类型的对象
【发布时间】:2013-04-23 21:16:06
【问题描述】:

我想像这样链式引用一个字符串属性:

echo($object1->object2->stringProperty);

但这会产生这个错误:

可捕获的致命错误:无法将类 [对象 2 的类型] 的对象转换为字符串

我可以通过在某处强制进行类型转换来完成这项工作吗?它可以为中间对象使用中间变量,但这增加了不幸的麻烦:

class foo {
    public $bar;
}

class bar {
    public $title;
}

// Initialize the example.
$myBar = new bar();
$myFoo = new foo();
$myFoo->bar = $myBar;
$myBar->title = "fubar";

// Using an intermediate object works.
$temp = $myFoo->bar;
echo("$temp->title<br />");

// Using a direct reference raises a fatal error.
echo("$myFoo->bar->title<br />");

【问题讨论】:

  • @sam-dufel $object 2 是一个对象。在上面的示例代码中,它是类栏。

标签: php oop chaining


【解决方案1】:

要么删除引号:

echo $myFoo->bar->title . "<br />";

或放在大括号中(也称为复杂语法):

echo "{$myFoo->bar->title}<br />";

【讨论】:

    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2011-06-06
    • 2015-01-18
    • 2021-01-19
    • 2017-07-27
    相关资源
    最近更新 更多