构造函数中的 Twig 加载器

Twig loader in constructor

我尝试使用 twig

做出自己的回应 class
<?php

namespace app\library;

class Response
{

public function __construct($temp, $data)
{
    $loader = new Twig_Loader_Filesystem('app/views');
    $twig = new Twig_Environment($loader);

    print $twig->render($temp, $data);
}
}

但是当我尝试使用它时

use app\library\Response;
error_reporting(E_ALL);
require_once "vendor/autoload.php";
$arr = array('name'=>'Bob', 'surname'=>'Dow', 'gender'=>'male','age'=>'25');
new Response('temp.php', $arr);

它给了我

Fatal error: Class 'app\library\Twig_Loader_Filesystem' not found in /var/www/PHP/app/library/Response.php on line 12

哪里错了?

请仔细检查错误。它说 class 'app\library\Twig_Loader_Filesystem' 不存在。您的响应 class 位于 app\library 命名空间下,因此您尝试实例化的每个 class 也会在该命名空间内查看。基本上和写

一样
$loader = new app\library\Twig_Loader_Filesystem('app/views');
$twig = new app\library\Twig_Environment($loader);

通常在这种情况下,您必须键入 class 的全名,包括其命名空间,或者像实例化 Response [=25 那样借助 use 语句创建 shorthand =].

在您的特定情况下,classes Twig_Loader_Filesystem 和 Twig_Environment 存在于全局名称空间中,因此您可以在 classes 前面添加 \ 以说明这些classes 位于全局命名空间中:

$loader = \Twig_Loader_Filesystem('app/views');
$twig = \Twig_Environment($loader);

或者像这样创建一个 shorthand:

use Twig_Loader_Filesystem;
use Twig_Environment;