Search code examples
phpcompiler-errorsgetnotice

How to solve this PHP notice error?


I am getting PHP notice error. This code was working fine in php 5.3 but then I upgraded my PHP to PHP 7. What I'm trying to do is, fetch the URL from the link, and just display the parameters attached with the URL. Here is the code.

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";
    }
?>

Output on going to URL: localhost/myDir/index.php/abc/def

Notice: Undefined index: controller in /srv/http/myDir/bootstrap.php on line 8
Notice: Undefined index: action in /srv/http/myDir/bootstrap.php on line 14

Home
index


Solution

  • Test for empty() ... that will be true for 0, '0', false, '', empty array() ... and the notice is gone also! ... Do the same for your other ifs and array indexes!

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

    To avoid similar warnings, you should also provide a default value in your methods, functions, etc. :

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