如何解决这个PHP通知错误


How to solve this PHP notice error?

我收到PHP通知错误。这段代码在php5.3中运行良好,但后来我将php升级到了PHP7。我想做的是,从链接中获取URL,然后只显示URL附带的参数。这是代码。

index.php

<?php 
    require_once('bootstrap.php');
    $bootstrap = new Bootstrap($_GET);
?> 

bootstrap.php

<?php 
class Bootstrap{
    private $controller;
    private $action;
    private $request;
    public function __construct($request){
        $this->request = $request;
        if($this->request['controller'] == ''){
            $this->controller = "Home";
        }
        elseif($_GET($request['controller'])){
            $this->controller = $this->request['controller'];
        }
        if($this->request['action'] == ''){
            $this->action = "index";
        } else{
            $this->action = $this->request['action'];
        }
        echo "<br />$this->controller<br />$this->action";
    }
?>

转到URL:localhost/myDir/index.php/abc/def的输出

注意:第8行/srv/http/myDir/bootstrap.php中的未定义索引:controller
注意:未定义的索引:第14行/srv/http/myDir/bootstrap.php中的操作

主页
索引

empty()测试。。。将为0的true,"0",false,",空数组()…通知也不见了!…对其他if和数组索引也执行同样的操作!

if(empty($this->request['action'])) {

为了避免类似的警告,您还应该在方法、函数等中提供默认值:

function ($arg=FALSE, $arg2=TRUE, $arg3=5, ...) {

如果您的代码运行良好&问题只是删除通知错误,然后您可以在php脚本中使用error_reporting(0)

添加error_reporting(0)作为php脚本中的第一条语句

测试是否已设置:isset($this->request['action'])isset($this->request['controller'])

像这样:

<?php 
class Bootstrap{
    private $controller;
    private $action;
    private $request;
    public function __construct($request){
        $this->request = $request;
        foreach ($request as $key => $value) {
            echo $key . " = " . $value;
        }
        if(isset($this->request['controller']) && $this->request['controller'] == ''){
            $this->controller = "Home";
        }
        elseif(isset($this->request['controller']) && $_GET($request['controller'])){
            $this->controller = $this->request['controller'];
        }
        if(isset($this->request['action']) && $this->request['action'] == ''){
            $this->action = "index";
        }
        else{
            $this->action = $this->request['action'];
        }
        echo "<br />$this->controller<br />$this->action";
    }
?>