【发布时间】:2017-12-06 02:31:09
【问题描述】:
我正在学习 laracast(https://laracasts.com/series/php-for-beginners) 的本教程,我正在观看该系列的这一集(16 - 制作路由器)
为了理解本教程中的某一部分,我做了很多事情,但我花了很多时间却无法理解。
教程是关于制作类似于laravel框架的路由系统
路由类
/**
* Created by PhpStorm.
* User: ahmadz
* Date: 7/2/2017
* Time: 7:30 PM
*/
class Router
{
public $route = [
'GET' => [],
'POST' => [],
];
public static function load($file)
{
$router = new static;
require $file;
return $router;
}
public function get($name, $path)
{
$this->route['GET'][$name] = $path;
}
public function uriProcess($uri, $method)
{
if(array_key_exists($uri,$this->route[$method])){
return $this->route[$method][$uri];
}
throw new Exception('Error in the uri');
}
}
routes file
$router->get('learn/try','controller/index.php');
$router->get('learn/try/contact','controller/contact.php');
索引文件
require Router::load('routes.php')->uriProcess(Request::uri(), Request::method());
当我将其更改为时出现问题
public static function load($file)
{
require $file;
}
我删除了这两行
$router = new static;
return $router;
然后在路由文件中实例化一个对象
$router = new Router;
$router->get('learn/try','controller/index.php');
$router->get('learn/try/contact','controller/contact.php');
当我这样做时,我会收到这些错误
致命错误:未捕获错误:调用成员函数 uriProcess() on 第 12 行 C:\xampp\htdocs\learn\try\index.php 中的 null (!) 错误: 在 null in 上调用成员函数 uriProcess() C:\xampp\htdocs\learn\try\index.php 在第 12 行
你能解释一下我不能在路由文件中实例化一个对象而不是加载函数吗?
【问题讨论】:
-
错误信息不是很明显吗?
-
我只是在问为什么我不能调用路由器文件中的对象而不是加载函数
-
路由器文件中没有该对象,而不是您拥有 NULL 的对象。这就是我问的原因,也许有关该错误消息的一些详细信息会有所帮助?
-
看看所有加载函数都需要一个文件。例如:“Router::load('routes.php')”可以说它需要路由文件,然后将返回的对象传递给该文件。我的问题是为什么我不能在 routes.php 文件中实例化一个对象,而不是在加载函数中这样做
-
很抱歉通知你,但是那个教程太可怕了。
标签: php class url-routing