php 在 null 上调用成员函数?

php Call to a member function on null?

我正在学习 laracast(https://laracasts.com/series/php-for-beginners) 中的教程,并且我正在观看系列中的这一集(16 - 制作路由器)

为了理解本教程中的一个部分,我做了各种各样的事情,但我花了很多时间还是没能理解。

本教程是关于制作类似于laravel框架的路由系统

路线class

/**
 * 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');

执行此操作时出现这些错误

Fatal error: Uncaught Error: Call to a member function uriProcess() on null in C:\xampp\htdocs\learn\try\index.php on line 12 ( ! ) Error: Call to a member function uriProcess() on null in C:\xampp\htdocs\learn\try\index.php on line 12

你能解释一下我不能在路由文件中实例化对象而不是加载函数的方法吗?

您已经删除了代码的重要部分。

在您的 load() 方法中,您实际上 实例化 路由器 class 然后 return 新的创建了 $router 对象。

当您删除以下行时:

   $router = new static;

   return $router;

方法 load() return 什么都没有,因此你会得到上述错误。

你要明白,你正在尝试使用 uriProcess() 方法,它是 class 路由器的一个方法,但是当你没有这种方法时,你如何期望这个方法工作你手里有什么东西吗?

您将不得不使用开头显示的代码:

public static function load($file)
{
    $router = new static;

    require $file;

    return $router;
}

编辑:

明白你的意思后,你可以试试下面的代码:

Router::load('routes.php');

$router = new Router;
$router->uriProcess(Request::uri(), Request::method());

$router->get('learn/try', 'controller/index.php');
$router->get('learn/try/contact', 'controller/contact.php');