symfony中的数组和对象问题


Array and object issue in symfony

我正在通过Symfony中的Action发送一个对象,但我无法在视图中检索它。

这是行动代码:

public function testphpAction()
    {
/*SOME DOCTRINE CODE*/
$productos = $consulta->getResult();
return $this->render('TPMainBundle:Default:test.html.php', array(
                'productos' => $productos,
    ));
}

我尝试了这个线程的解决方案,但没有付出任何努力:PHP错误:无法将stdClass类型的对象用作数组(数组和对象问题(

这是我的视图"test.html.php"的代码:

foreach($productos as $producto) {
    echo $producto['descripcion'];
}
// This displays the error: "Cannot use object of type TP'MainBundle'Entity'Works as array

所以我尝试了另一个线程的解决方案:

foreach ($productos as $producto) {
        $id         = $producto->id;
        echo $id;
//But it throws the error: Cannot access private property TP'MainBundle'Entity'Works::$id

两者都不起作用:

$id = $productos->id;
// Throw: "Trying to get property of non-object"

我如何访问它?如果我渲染到一个小树枝模板,我不会有这个问题,但我需要使用php。

$productos的var_dump是这样的:(我提交了这个链中的其他对象(

array(3) { [0]=> object(TP'MainBundle'Entity'Works)#290 (4) { ["id":"TP'MainBundle'Entity'Works":private]=> int(1) ["descripcion":"TP'MainBundle'Entity'Works":private]=> string(30) "Landing page for a toys store." ["img":"TP'MainBundle'Entity'Works":private]=> string(12) "images/1.jpg" ["preview":"TP'MainBundle'Entity'Works":private]=> string(13) "images/1m.jpg" }

定义getter,然后使用它们。

例如在这个中

foreach ($productos as $producto) 
{ $id = $producto->id; echo $id; }

尝试

$producto->getId(); 

而不是

 $producto->id;

假设您定义了getter。

$id         = $producto->id;

这将不起作用,因为无论该属性是不可公开访问的,还是对象没有该属性。

Work对象有description,但它是私有的,所以您必须创建一个getter函数来回显它

例如

echo $producto->getDescription();