【问题标题】:require is working but require_once is notrequire 正在工作,但 require_once 不是
【发布时间】:2015-09-29 09:51:32
【问题描述】:

Routes.php

use MyMVC\Core\Route;

$route = new Route;
$route->add('/', 'HomeController@index');
$route->add('about', 'AboutController@index');
$route->add('contact', 'ContactController@index');

Index.php

<?php
/**
 * Define Constants
 */
define('BASE_PATH', dirname(realpath(__FILE__)));
define('APP_PATH', BASE_PATH . "/app");

/**
 * Including the Composer's autoloader
 */
require_once 'vendor/autoload.php';

/**
 * Load the routes declarations
 */
require_once 'app/routes.php';

/**
 * Bootstrap our application
 */
require_once 'app/init.php';

/**
 * Initialize our beautiful framework
 */
$application = new \MyMVC\Application($route);

composer.json

"autoload" : {
    "psr-4" : {
        "MyMVC\\" : "app/"
    },
    "classmap": [
        "app/Controllers",
        "app/Helpers"
    ],
    "files": ['app/routes.php']  // already removed this line
},

当使用require_once 时,它会给出undefined variable route error,而如果我只使用require,它会显示路由对象。

为什么会这样?

【问题讨论】:

  • 一定是其他原因导致了这个问题,如The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.
  • 可能它早先包含在脚本中,因此不再需要它?
  • @chriz 更新我的代码。这就是index.php 的全部内容。
  • 添加您的composer.json
  • 你跑composer dump-autoload了吗?

标签: php


【解决方案1】:

仅当文件已从其他文件加载时才会发生这种错误。这就是为什么它没有再次加载它并且你没有得到 $route 对象的实例。

例如,

让我们说 file1.php 包含 routes.php

现在如果你使用:

  1. 需要'routes.php'(即使已经加载,它也会再次加载相同的文件

  2. requier_once 'routes.php'(如果文件已经加载,它将不会加载,并且你没有得到 $route 变量的实例,这意味着它正在发生

【讨论】:

  • 第 2 点说(如果已经加载,它将不会加载文件)。如果是这样,仍然 $route 实例应该可用。
  • 但是当且仅当文件没有作为变量实例加载到函数或类中时,那么只能从那里获取
  • 是的,你可以在我上面的代码中看到 routes.php 不是类也不是函数。
  • 您的简单答案是使用 GLOBAL $route;现在,即使在任何范围内加载,您也将始终获得该变量。希望你明白:)
【解决方案2】:

所有症状都表明“app/routes.php”之前包含在其他地方。由于它定义了一个变量,如果这样的包含没有发生在全局范围内,该变量将是本地的,无论它是从哪里调用的。

除了使用 Xdebug 等专用调试器外,您还可以使用内置工具来诊断问题。例如,您有get_included_files() 来获取给定点中包含文件的列表。您还可以在 'app/routes.php' 顶部添加 debug_print_backtrace() 以找出调用它的位置。

关于更新问题和后续评论的说明:如果您尝试自动加载文件并且文件会自动加载,我会说您刚刚回答了自己的问题.但值得注意的是,自动加载旨在用于函数和类定义。您有一个任意代码 sn-p 定义了一个变量,并且——正如你刚刚了解到的——因为该变量成为自动加载器方法的本地变量,所以它没有多大用处。

【讨论】:

  • 我对您的回答有很大帮助,但我想找出一件事很多天。我使用了通过composer自动加载的文件,并加载了routes.php。这是否意味着 routes.php 现在将自动可用?
猜你喜欢
  • 2021-07-05
  • 2011-04-02
  • 2015-10-31
  • 1970-01-01
  • 2016-10-16
  • 2010-11-12
  • 2015-07-24
  • 2014-09-20
  • 2011-12-08
相关资源
最近更新 更多