注意:未定义变量:twig

时间:2019-04-09 08:38:11

标签: php twig

我不知道如何在作曲控制器中使用

1 composer.json:

"require": {
        "php": ">=7.2.0",
        "filp/whoops": "*",
        "noahbuscher/macaw": "dev-master",
        "twig/twig": "^2.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "App/"
        },
        "files":[]
    }

2个控制器:

控制器   | -HomeController.php   | -ShareControllers.php

3 ShareControllers.php:

<?php


namespace  App\Controllers;


class ShareControllers
{
    public function __construct()
    {

        $loader = new \Twig\Loader\FilesystemLoader(VIEW_PATH);
        $twig = new \Twig\Environment($loader, [
            'cache' => CACHE_PATH,
            'debug' => true
        ]);

    }
}

4 HomeController.php:

namespace  App\Controllers;


class HomeController extends ShareControllers
{
    public function index(){
        echo $twig->render('content.html', ['name' => 'hi']);
    }

}

如此:

Notice: Undefined variable: twig  :(

1 个答案:

答案 0 :(得分:3)

这是一个范围界定问题。当前,您只是将树枝实例存储在只能在该方法范围内访问的局部变量中。您需要将其添加为类属性:

class ShareControllers
{
    protected $twig;

    public function __construct()
    {    
        $loader = new \Twig\Loader\FilesystemLoader(VIEW_PATH);

        // Adding $this-> will store it in the above defined property
        $this->twig = new \Twig\Environment($loader, [
            'cache' => CACHE_PATH,
            'debug' => true
        ]);
    }
}

现在,在子类中,您可以使用:

class HomeController extends ShareControllers
{
    public function index(){
        // Here we also use $this-> to fetch the instance
        echo $this->twig->render('content.html', ['name' => 'hi']);
    }

}

我建议您阅读有关class propertiesvariable scopes的手册。