ramiromd
ramiromd

Reputation: 2029

Class not found using namespace

I have an class called Alumno.class.php, locate in Root\Classes\Abm\Alumno.class.php. So this class header is:

/**
 * Gestiona las operaciones ABM del tipo de usuario alumno.
 * La clase no realiza validaciones, eso será labor del controlador.
 * @package AdminManantiales
 * @subpackage Abm
 * @author Ramiro Martínez D'Elía
 */

namespace AdminManantiales\Classes\Abm;

class Alumno extends Usuario{ // Implement }

Now, I need to use the class in a php script, and try with this:

use \AdminManantiales\Classes\Abm\Alumno as AbmAlumno;
[...]
// Proceso el alta.
$alumno = new AbmAlumno();
$alumno->alta($_POST);
$nombreCompleto = $alumno->toStr();

But it fails in the $alumno = new AbmAlumno(); line. With the next message:

Class 'AdminManantiales\Classes\Abm\Alumno' not found

How do I include correctly the class using the "use" keyword ?.

Upvotes: 2

Views: 7721

Answers (2)

timhc22
timhc22

Reputation: 7451

You can also use autoloading with composer (App and src/ would be different for you though):

{
    "require": {

    },
    "autoload": {
        "psr-0": {
            "App": "src/"
        }
    }
}

You might also have to run composer.phar dumpautoload in the console.

Upvotes: 2

federicot
federicot

Reputation: 12331

The use keyword doesn't actually do anything. You'll have to either include the PHP script manually, using include \AdminManantiales\Classes\Abm\Alumno.php (or whatever the filepath is) or use autoloading like this,

function autoload($classId)
{
    $classIdParts       = explode("\\", $classId);
    $classIdLength      = count($classIdParts);
    $className          = strtolower($classIdParts[$classIdLength - 1]);
    $namespace          = strtolower($classIdParts[0]);

    for ($i = 1; $i < $classIdLength - 1; $i++) {
        $namespace .= '/' . $classIdParts[$i];
    }

    if (file_exists(dirname(__FILE__)) 
        . '/' . $namespace 
        . '/' . $className 
        . '.class.php') {
        include $namespace . '/' . $className . '.class.php';
    }
}

spl_autoload_register('autoload');

You can then store this script and include it whichever script you use the use keyword.

Upvotes: 5

Related Questions