尝试访问PHP中null类型值的数组偏移量



我的Core.php文件中有以下代码:

<?php 
/*
* App Core Class
* Creates URL and 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 part of URL
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
// $pages = new Pages;
$this->currentController = new $this->currentController;
// Check for second part of URL
if(isset($url[1])){
// Check to see if method exists in controller
if(method_exists($this->currentController, $url[1])){
$this->currentMethod = $url[1];
// Unset 1 Index
unset($url[1]);
}
}
// Get params
// Array([[0] => 'about', [1] => 1])
$this->params = $url ? array_values($url) : [];
// Call a callback with array of params
call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
}
public function getUrl(){
if(isset($_GET['url'])){
$url = rtrim($_GET['url'], '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
return $url;
}
}
}

/controllers/Pages中加载我的控制器时,其中包含以下代码:

<?php
class Pages {
public function __construct(){

}
public function index(){
echo "This is index method!";
}
public function about($id){
echo "This is about method and the id passed is " . $id;
}
}

它是这样说的:

/Applications/XAMPP/xamppfiles/htdocs/mvc/app/libraries/core.php中尝试访问null类型值的数组偏移在线19

这属于我的core.php文件中的这一行:

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

老实说,我不确定这是什么意思。谁能指出是什么导致了这个错误,即使我在控制器上有默认的索引方法?

提前感谢。

$url[0]数组变量未设置。这就是错误的原因。请在检查文件前添加if语句,如

if(isset($url[0])){
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]);
}
}

相关内容

最新更新