php - 加载命名空间(具有不同名称)所需的文件?

标签 php class namespaces

我有两个文件,如下所述:

路径:index.php

<?php
// Composer autload
require_once 'vendor/autoload.php';

//The commented code below works:
//$loader = new Twig_Loader_String();
//$twig = new Twig_Environment($loader);
//echo $twig->render('Hello {{ name }}!', array('name' => 'Fabien'));

//Bad proposal solution. How to avoid to explicit load all files with namespaces?
//  Please see the 'Important edit' below.
//include_once 'Core/Twig/Twig.php';
use Core\Twig\Twig as Twig;

$twig = new Twig();
var_dump($twig);

路径:Core/Twig/Twig.php

<?php
namespace Core\Twig;

class Twig
{
    public function configure()
    {
        $loader = new \Twig_Loader_String();
        $twig = new \Twig_Environment($loader);
        //just for testing
        echo $twig->render('Hello {{ name }}!', array('name' => 'Fabien'));
    }
}

但是我遇到了 fatal error :未找到类“Core\\Twig\\Twig”

我该如何解决这个问题?

P.S.:我尝试了命名空间的一些变体(例如 Core\TwigCore)、use(例如 TwigCore\TwigCore\Twig as Twig)和新的(如 Twig\Twig()Core\Twig )。不幸的是,没有任何效果。

重要编辑: 我明白为什么 php 没有找到该类。需要像 include_once 'Core/Twig/Twig.php' 这样的行。但问题仍然存在......我怎样才能避免这种情况呢?避免包含所有带有命名空间的文件?或者,如何在需要时自动加载这些文件?

最佳答案

您可能错误地标记了命名空间。查看“命名空间导入:use 关键字”部分 in this namespace primer.

路径:lib/vendor/core/Twig.php

<?php
namespace lib\vendor\core;

class Twig
{
    //Your code
}

路径:index.php

use lib\vendor\core\Twig;
$twig = new Twig();
var_dump($twig);

关于php - 加载命名空间(具有不同名称)所需的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15599521/

相关文章:

php - 没有 ON 子句的 Doctrine DBAL 连接

php - 如何从 Yelp API 获取网站

php - WordPress 类别列表 RSS 提要

c++ - 有没有办法声明一个类,然后在 C++ 的函数中初始化它?

arrays - typescript :具有属性/数组作为类的数组

c# - 数据库中的 Entity Framework 生成命名空间错误

php - 仅可通过登录用户页面访问

javascript - 如何获取es6类实例的所有函数

c++ - 在什么情况下全局运算符隐藏在 C++ 中?

namespaces - node.js 中的“全局”对象