pedro.olimpio
pedro.olimpio

Reputation: 1498

Class autoload not working

I'm a beginner in PHP development and I'm facing a problem in my development in PHP OO. I saw is better use the autoload() function than include each file of PHP Class.

My doubt is: Why my autoload function does not work?

Follow bellow my code:

<?php
function __autoload($class)
{
    include_once "model/{$class}.class.php";
}

$avaliacaoLocal = new AvaliacaoLocal();
$avaliacaoLocal->setId(1);
$avaliacaoLocal->setIdLocal(2);
$avaliacaoLocal->setComentarios("Comentários de Pedro");
$avaliacaoLocal->setIdPessoaCliente(3);
$avaliacaoLocal->setValor(5);
var_dump($avaliacaoLocal);

File AvaliacaoLocal.class.php

<?php
namespace model;

class AvaliacaoLocal
{
    private $id;
    private $valor;
    private $comentarios;
    private $idLocal;
    private $idPessoaCliente;

    public function __construct(){

        $this->clear();

    }

    public function clear(){

        $this->id = 0;
        $this->valor = 0;
        $this->comentarios = "";
        $this->idLocal = null;
        $this->idPessoaCliente = null;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getValor()
    {
        return $this->valor;
    }

    public function setValor($valor)
    {
        $this->valor = $valor;
    }

    public function getComentarios()
    {
        return $this->comentarios;
    }


    public function setComentarios($comentarios)
    {
        $this->comentarios = $comentarios;
    }

    public function getIdLocal()
    {
        return $this->idLocal;
    }

    public function setIdLocal($idLocal)
    {
        $this->idLocal = $idLocal;
    }

    public function getIdPessoaCliente()
    {
        return $this->idPessoaCliente;
    }

    public function setIdPessoaCliente($idPessoaCliente)
    {
        $this->idPessoaCliente = $idPessoaCliente;
    }

}

The error:

PHP Fatal error: Class 'AvaliacaoLocal' not found in C:\Users\Pedro ........\index.php on line 14

UPDATE:

When i use include the PHP returns the same error:

Fatal error: Class 'AvaliacaoLocal' not found in C:\Program Files\VertrigoServ\www\system\index.php on line 10

i've change folder to verify if could be it.

Upvotes: 1

Views: 5640

Answers (1)

CJ Nimes
CJ Nimes

Reputation: 658

The class is declared belonging to a namespace, you have to call it in this way:

$avaliacaoLocal = new \model\AvaliacaoLocal();

But now, the namespace is also included in $class, so the autoload function needs to handle that:

function __autoload($class)
{
    $file = str_replace(array('_', '\\'), '/', $class) . '.php';

    if (is_file($file)) {
        require $file;
    }
}

This function takes $class value and replace every \ (and _) from the namespace with a / to get the file name.

Upvotes: 2

Related Questions