【问题标题】:URL is not working when it's trying it for routingURL 在尝试路由时不起作用
【发布时间】:2018-06-04 10:50:53
【问题描述】:

我正在尝试从我的本地主机中获取 URL,这里是 http://localhost/mvc/index.php?url=Index/category 一切进展顺利,但是当我尝试使用 URL /category 时,它显示错误。这是错误

注意:第 21 行 C:\xampp\htdocs\mvc\index.php 中的数组到字符串转换

注意:未定义的属性:第 21 行 C:\xampp\htdocs\mvc\index.php 中的 Index::$Array

致命错误:未捕获的错误:函数名称必须是 C:\xampp\htdocs\mvc\index.php:30 中的字符串 堆栈跟踪:#0 {main} 在 C:\xampp\htdocs\mvc\index 中抛出.php 在第 21 行

<?php
include_once "system/libs/main.php";
include_once "system/libs/Dcontroller.php";
include_once "system/libs/Load.php";
?>
<?php
$url = isset($_GET['url']) ? $_GET['url'] : NULL;
if ($url != NULL) {
    $url = rtrim($url,'/');
    $url = explode("/", filter_var($url,FILTER_SANITIZE_URL));
} else {
    unset($url);
}
if (isset($url[0])){
    include 'app/controllers/'.$url[0].'.php';
    $ctlr = new $url[0]();
    if (isset($url[2])) {
        $ctlr->$url[1]($url[2]);
    } else {
        if (isset($url[1])) {
            $ctlr->$url[1]();  //Here is the line where I'm getting the 
                                 error
        } else {

        }           
    }

}else{
    include 'app/controllers/Index.php';
    $ctlr = new Index();
    $ctlr->home(); 
}   
?>

但是当我使用 category() 而不是 $url[1] 它工作正常。这是索引类。

<?php
class Index extends Dcontroller
{   
    public function __construct()
    {
        parent::__construct();
    }
    public function home()
    {
        $this->load->view("home");
    }
    public function category()
    {
        $data = array();
        $catModel = $this->load->model("CatModel");
        $data['cat'] = $catModel->catList();
        $this->load->view("category", $data);
    }
}

【问题讨论】:

标签: php url-routing


【解决方案1】:

两件事:“/”在作为获取字符串的一部分的 url 参数中是不合法的。你需要用 URL 编码封装它

EG:

  http://localhost/mvc/index.php?url=Index%2Fcategory

这也是"$ctlr-&gt;$url[1]" 根本没有调用它的函数的事实。例如:"$ctlr-&gt;$url[1]" 解析为 ??category()??不存在,你需要制作它。

将此添加到您的代码中

 function category() {
       Index tmp = new Index();
       tmp->category();
 }

编辑:我刚刚注意到,这比我想象的还要愚蠢.. 你的字符串说 Index/category 不是吗?.. 使类方法静态.. (这段代码可怕的是它几乎没有任何设计知识)没有Index/category,因为你不能在一个类中调用category,除非它是一个静态方法。

学习编码。

【讨论】:

  • Index 类中有函数 category(),但我发现使用 URL 路由访问该函数有困难。希望你能理解。
  • 这就是我封装它的原因,错误说它在您的范围内不存在..(所以它不存在!)...而是存在一个类方法(编辑@ 987654331@)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多