面向对象样式PHP中的命名空间用法

时间:2012-07-26 14:49:21

标签: php namespaces

我一直在使用PHP中的命名空间摆弄并尝试使其工作,但它失败了

让我展示示例代码:

测试\视图\类\ MainController.php

<?php
namespace test\views\classes;

class MainController
{
    public function echoData()
    {
        echo 'ECHOD';
    }
}

测试\视图\的index.php

<?php
require_once '..\autoloader\autoloader.php';

use test\views\classes\MainController;

$cont = new MainController();

$cont->echoData();

测试\自动装载机\ autoloader.php

<?php

spl_autoload_register(null, FALSE);

spl_autoload_extensions('.php');


function classLoader($class)
{
    $fileName = strtolower($class) . '.php';

    $file = 'classes/' . $fileName;

    if(!file_exists($file))
    {
        return FALSE;
    }

    include $file;
}

spl_autoload_register('classLoader');

引发错误:

Fatal error: Class 'test\views\classes\MainController' not found in ..\test\views\index.php on line 6

我错过了什么!

编辑:当index.php和maincontroller.php在不使用自动加载器但使用require_once('maincontroller.php')的同一目录中时,代码工作正常; 如果它们位于不同的目录中并且具有自动加载器功能,则不起作用。任何人都可以解决这个问题。

由于

2 个答案:

答案 0 :(得分:1)

代码中存在多个问题:

命名空间分隔符(\)不是Linux / Unix中的有效路径分隔符。您的自动加载器应该执行以下操作:

$classPath = str_replace('\\', '/', strtolower($class)) . '.php';
if (!@include_once($classPath)) {
 throw new Exception('Unable to find class ' .$class);
}

另外,路径都是相对的。您应该设置包含路径。如果您的网站结构如下:

bootstrap.php
lib/
  test/
    views/
      index.php
      classes/
        maincontroller.php
  autoloader/
    autoloader.php

你的bootstrap.php应该类似于:

$root = dirname(__FILE__);
$paths = array(
    ".",
    $root."/lib",
    get_include_path()
);
set_include_path(implode(PATH_SEPARATOR, $paths));
include 'lib/test/autoloader/autoloader.php';

现在,在test / views / index.php中,您可以只包含引导程序:

include '../../bootstrap.php';

答案 1 :(得分:0)

将die语句添加到类加载器:

$file = 'classes/' . $fileName;

die('File ' . $file . "\n");

你得到了

File classes/test\views\classes\maincontroller.php

这真的是您的主控制器类所在的位置吗?

相关问题