使用名称空间找不到类 [英] Class not found using namespace

查看:83
本文介绍了使用名称空间找不到类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Alumno.class.php的类,位于Root \ Classes \ Abm \ Alumno.class.php中. 所以这个类头是:

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 }

现在,我需要在php脚本中使用该类,然后尝试以下操作:

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();

但是它在$alumno = new AbmAlumno();行中失败.随着下一条消息:

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

找不到"AdminManantiales \ Classes \ Abm \ Alumno"类

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

如何使用"use"关键字正确包含该类?

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

推荐答案

use关键字实际上 没有任何作用.您必须使用include \AdminManantiales\Classes\Abm\Alumno.php(或其他文件路径)手动添加 PHP 脚本,或者使用<像这样的href ="http://php.net/manual/zh/language.oop5.autoload.php" rel ="noreferrer">自动加载,

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');

然后,您可以存储此脚本并包括使用use关键字的任何脚本.

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

这篇关于使用名称空间找不到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆