Trying to access array offset on value of type null

I get this error - Notice : Trying to access array offset on value of type null in C:\xampp\htdocs\OAMVC\app\libraries\Core.php on line 18 .

Not sure why, been trying to find the solution for hours.

//core.php
<?php
  /*
   * App Core Class
   * Creates URL & loads core controller
   * URL FORMAT - /controller/method/params
   */
  class Core {
    protected $currentController = 'Pages';
    protected $currentMethod = 'index';
    protected $params = [];

    public function __construct(){
      //print_r($this->getUrl());

      $url = $this->getUrl();

      // Look in controllers for first value
      if(file_exists('../app/controllers/' . ucwords($url[0]). '.php')){
        // If exists, set as controller
        $this->currentController = ucwords($url[0]);
        // Unset 0 Index
        unset($url[0]);
      }

      // Require the controller
      require_once '../app/controllers/'. $this->currentController . '.php';

      // Instantiate controller class
      $this->currentController = new $this->currentController;
    }

    public function getUrl(){
      if(isset($_GET['url'])){
        $url = rtrim($_GET['url'], '/');
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $url = explode('/', $url);
        return $url;
      }
    }
  } 
// Pages.php
<?php

class Pages {
    public function __construct(){
        echo 'Pages loaded';    
    }
}

So,

 if(file_exists('../app/controllers/' . ucwords($url[0]). '.php')){

If we take a look at how you get that array,

 public function getUrl(){
      if(isset($_GET['url'])){
        $url = rtrim($_GET['url'], '/');
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $url = explode('/', $url);
        return $url;
      }
    }

In other words, you are not getting a url variable in the uri to get an array back.

Sorry I am not too sure what you mean. Are you saying I didn’t define the get url in a variable before returning it?

For there to be a null, the getUrl function didn’t return anything. I would add a log or a string that says the url was not passed so you can see what actually happened.

Ahh I see where I went wrong. Thanks!

1 Like

Hello,

i have the same issue… Can you explain me where was the mistake please?
Thank a lot.

Create a new topic and post your code.

Sponsor our Newsletter | Privacy Policy | Terms of Service