以下に説明するように2つのファイルがあります。
パス: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'));
}
}
しかし、致命的なエラーが発生していますClass 'Core\\Twig\\Twig' not found
。
どうすればこれを解決できますか?
PS:名前空間(、のような)、使用(、、のような)、および新しい(、のような)にいくつかCore\Twig
のCore
バリエーションTwig
を試しCore\Twig
ました。残念ながら、何も機能しません。Core\Twig as Twig
Twig\Twig()
Core\Twig
重要な編集:
phpがクラスを見つけられなかった理由を理解しました。のようなラインinclude_once 'Core/Twig/Twig.php'
が必要でした。しかし、問題はまだ続いています...どうすればこれを回避できますか?名前空間を持つすべてのファイルを含めることを避けますか?または、必要なときにこのファイルを自動ロードするにはどうすればよいですか?