Problems with data type in array within a class

0

I'm using PHP/PDO with DAO and VO .

This is the index.php:

<?php
    require ('includes/config.php');
    $DAO = new TrabajoDAO();
    $listas = $DAO->Listar();
    $tpl = new Plantilla();
    $tpl->assign('lista', $listas);
    $tpl->display("crud.tpl.php");
?>

This is the file TrabajoVO.class.php

<?php
    class TrabajoVO {
        private $codigo;
        private $nombre;

        public function TrabajoVO($codigo, $nombre) {
            $this->codigo = $codigo;
            $this->nombre = $nombre;
        }
    }
?>

This is the file TrabajoDAO.class.php

<?php
    class TrabajoDAO {

        public function __construct(){
        }

    public function Listar()
    {
        try
        {
            $BD = new ConexionDB();
            $stm = $BD->prepare("SELECT codigo, nombre FROM tabla");
            $stm->execute();
            foreach($stm->fetchAll(PDO::FETCH_OBJ) as $fila)
            {
                $resultado[] = new TrabajoVO($fila['codigo'], $fila['nombre']);
            }
            return $resultado;
        }
        catch(Exception $e)
        {
            die($e->getMessage());
        }
    }

        public function __destruct(){
        }
    }
?>

This is the template:

{section name=i loop=$lista}
<tr class="success">
    <td class="text-center">{counter}</td>
    <td class="text-center">{$lista[i]->codigo}</td>
    <td class="text-center">{$lista[i]->stud}</td>
</tr>
{/section}

When I run it, this message appears:

  

Fatal error: Can not use object of type stdClass as array

on the line of $resultado[] of TrabajoDAO .

    
asked by Piropeator 05.06.2017 в 22:35
source

1 answer

-1

You must declare the array $ result before using it in the loop:

<?php
    class TrabajoDAO {

        public function __construct(){
        }

    public function Listar()
    {
        try
        {
            $resultado = array();
            $BD = new ConexionDB();
            $stm = $BD->prepare("SELECT codigo, nombre FROM tabla");
            $stm->execute();
            foreach($stm->fetchAll(PDO::FETCH_OBJ) as $fila)
            {
                $resultado[] = new TrabajoVO($fila['codigo'], $fila['nombre']);
            }
            return $resultado;
        }
        catch(Exception $e)
        {
            die($e->getMessage());
        }
    }

        public function __destruct(){
        }
    }
?>
    
answered by 05.06.2017 в 23:21