Php require正在工作,但require\u once不起作用
Routes.phpPhp require正在工作,但require\u once不起作用,php,Php,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 use MyMVC\Core\Route; $route = new
use MyMVC\Core\Route;
$route = new Route;
$route->add('/', 'HomeController@index');
$route->add('about', 'AboutController@index');
$route->add('contact', 'ContactController@index');
Index.php
use MyMVC\Core\Route;
$route = new Route;
$route->add('/', 'HomeController@index');
$route->add('about', 'AboutController@index');
$route->add('contact', 'ContactController@index');
<?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);
当使用require\u一次时
会给出未定义的变量路由错误
,而如果仅使用require
则会显示路由对象
为什么会这样?所有症状都表明“app/routes.php”以前包含在其他地方。因为它定义了一个变量,如果这样的包含没有发生在全局范围内,那么这个变量将是本地变量,无论从哪里调用它 除了使用Xdebug之类的专用调试器外,还可以使用内置工具诊断问题。例如,您必须获得给定点中包含的文件列表。您还可以添加到“app/routes.php”的顶部,以了解从何处调用它
关于更新的问题和后续评论的注意事项:如果您试图自动加载文件,并且文件会自动加载,我认为您刚刚回答了自己的问题。但值得注意的是,自动加载旨在用于函数和类定义。您有一个定义变量的任意代码段,正如您刚刚了解到的,由于该变量成为自动加载程序方法的本地变量,因此没有多大用处。这种错误仅在文件已从其他文件加载时发生。这就是为什么它不会再次加载它,也不会得到$route对象的实例
use MyMVC\Core\Route;
$route = new Route;
$route->add('/', 'HomeController@index');
$route->add('about', 'AboutController@index');
$route->add('contact', 'ContactController@index');
例如
比方说
file1.php包含routes.php
use MyMVC\Core\Route;
$route = new Route;
$route->add('/', 'HomeController@index');
$route->add('about', 'AboutController@index');
$route->add('contact', 'ContactController@index');
<?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);
现在,如果您使用:
问题一定是由其他原因引起的,因为require\u once语句与require语句相同,只是PHP会检查文件是否已包含,如果已包含,则不会再次包含(require)该文件。可能是该文件之前已包含在脚本中,因此不再需要它?@chriz updated my code。这是所有的
index.php
都是关于。添加你的composer.json
。你是否运行了composer dump autoload
?第2点说(如果已经加载,它将不会加载文件)。如果是这样的话,$route实例仍然是可用的。但是,如果且仅当文件没有作为变量实例加载到函数或类中,那么只能从中获取。您可以在routes上面的代码中看到。php既不是类,也不是函数。您的简单答案是使用全局$route;现在,即使在任何范围内加载,也将始终获得该变量。希望你能明白:)我对你的答案有很大的帮助,但有一件事我一直在努力寻找。我使用了通过composer自动加载的文件,并加载了routes.php。这是否意味着routes.php现在将自动可用?