Array and object issue in symfony

时间:2015-08-14 22:44:04

标签: php arrays symfony

I'm sending an object via my Action in Symfony, but I cannot retrieve it in my view.

This is the Action code:

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

I tried the solutions from this thread but with no effort: PHP Error: Cannot use object of type stdClass as array (array and object issues)

This is the code of my view '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

So I tried the solution from the other thread:

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

Neither this worked:

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

How can I access it? I don't have this problem if I render to a twig template, but I need to use php.

The var_dump of $productos is this: (I ommited the other objects in this chain)

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" }

2 个答案:

答案 0 :(得分:1)

Define your getters, and then use them.

for example in this

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

Try

$producto->getId(); 

instead of

 $producto->id;

assuming you defined your getter.

答案 1 :(得分:0)

$id         = $producto->id;

This won't work because whether the property is not publicly accessible or the Object does not have that property.

The Work object has description, but it's private, so you'd have to create a getter function to echo it.

e.g

echo $producto->getDescription();