0

I try to make my own Response class using twig

<?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);
}
}

But when I try to use it

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

It gives me

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

Where the mistake?

Torondor
  • 40
  • 6

1 Answers1

1

Please check carefully the error. It says that class 'app\library\Twig_Loader_Filesystem' doesn't exists. Your Response class is under app\library namespace so every class which you try to instantiate there will be looked inside this namespace as well. Basically it's the same as write

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

Generally in this case you have to either type the full name of a class including its namespace or make the shorthand with the help of use statement like you did for instantiating Response class.

In your particular case classes Twig_Loader_Filesystem and Twig_Environment exist in a global namespace so you could either add \ in front of classes to state that these classes are located in a global namespace:

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

or create a shorthand like this:

use Twig_Loader_Filesystem;
use Twig_Environment;
ConstantineUA
  • 1,051
  • 1
  • 9
  • 18