【问题标题】:How to solve this PHP notice error?如何解决这个 PHP 通知错误?
【发布时间】:2016-07-29 12:50:34
【问题描述】:

我收到 PHP 通知错误。这段代码在 php 5.3 中运行良好,但后来我将 PHP 升级到 PHP 7。我想做的是,从链接中获取 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 中的控制器
注意:未定义索引:第 14 行 /srv/http/myDir/bootstrap.php 中的操作

首页
索引

【问题讨论】:

标签: php compiler-errors get notice


【解决方案1】:

测试empty() ...这将是true for 0, '0', false, '', empty array() ...通知也消失了! ... 对你的其他 if 和数组索引做同样的事情!

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 如果他不得不迁移到其他编程语言(如 C 或 Java),这是非常糟糕的“解决方法”。它只是隐藏了错误/警告,但没有解决它。
    • 不!这是不好的编程习惯。你可以在上网时这样做(但是,所有这些警告和通知无论如何都应该过时了)
    • 实际上它不起作用。它应该在索引上显示 abc 而不是 Home 和 def 而不是。所以我猜这个错误也会影响输出。
    【解决方案3】:

    测试 isset : isset($this-&gt;request['action']) isset($this-&gt;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";
        }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多