【问题标题】:Warning: Trying to access array offset on value of type null in C:警告:尝试访问 C 中 null 类型值的数组偏移量:
【发布时间】:2021-10-29 18:21:45
【问题描述】:

嗨,我这周一直在为这个项目工作,我正在帮助我儿子完成他的学校项目,该项目是一个使用 MVC 设计的 PHP 登录脚本,一切都在运行,但我不断收到以下警告:尝试访问第 18 行 C:\wamp64\www\mvloginregister\app\libraries\Core.php 中 null 类型值的数组偏移量,第 18 行代码如下:

// Look in BLL for first value
 18 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]);
  }
I think the issue is in the following function 
public function getUrl(){
  if(isset($_GET['url'])){
    $url = rtrim($_GET['url'], '/');
    $url = filter_var($url, FILTER_SANITIZE_URL);
    $url = explode('/', $url);
    return $url;
  }
}

我已在此站点上查看了与此问题相关的所有推荐答案,但我无法解决此问题认为是粗鲁和不专业的。请帮助我对这种 php 语言和 MVC 设计非常陌生。

【问题讨论】:

  • $url 变量不存在,但您将其视为存在并包含一个数组。请注意,如所写,如果 URL 中没有 url 参数,getUrl() 不会返回任何内容。您可能希望检测到这种情况并在它发生时提供 404 页面。
  • $url 变量确实存在 $url = $this->getUrl(); // 在 BLL 中查找第一个值 if(file_exists('../app/controllers/' . ucwords($url[0]). '.php')){ // 如果存在,设置为控制器 $this-> currentController = ucwords($url[0]); // 取消设置 0 索引 unset($url[0]); }
  • $url = $this->getUrl(); 好的,您没有在原始帖子中包含该内容。尽管如此,它还是空的,但您的代码假定它始终是一个包含至少一个元素的数组。

标签: php arrays model-view-controller pdo offset


【解决方案1】:

今天我遇到了同样的问题,在网上也找不到任何解决方案。 最后我自己解决了:将 $url 变量添加到“if”语句中的条件中。这不仅会检查文件是否存在,还会检查 $url 是否不为空 - 就像这样:

 $url = $this->getUrl();
 
  if( $url && file_exists('../app/controllers/' . ucwords($url[0]). '.php') ){
   
    $this->currentController = ucwords($url[0]);
    
    unset($url[0]);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2021-07-23
    • 2023-01-10
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多