zoukankan      html  css  js  c++  java
  • Trying to get property of non-object_thinkphp路由报错

    在阅读《thinkphp5.0快速入门》这本书时,模型基础这一节碰到一点路由上的问题。在此随笔记一下。

    碰到的问题:

    [8] ErrorException in UserController.php line 43

    Trying to get property of non-object

    Controller.php

    public function read($id=''){
        $user = Usermodel::get($id);
        echo "-----------function read() running...-----------<br/>";
        echo "id : ".$id."<br/>";
        echo $user->nickname.'<br/>';
        echo $user->email.'<br/>';
        echo date('Y/m/d', $user->birthday).'<br/>';
    }
    public function read2($id=''){
        $user = Usermodel::get($id);
        echo "-----------function read2() running...-----------<br/>";
        echo "id : ".$id."<br/>";
        echo $user['nickname']."<br/>";
        echo $user['email']."<br/>";
        echo date('Y/m/d', $user['birthday'])."<br/>";
    }

    碰到这个问题,是因为在路由中添加了与教程不一样的路由规则。教程中定义了一条规则:

    'user/:id'        => 'index/user/read',

    这样在浏览器输入http://www.mjtest.com/user/3, 就能访问到read方法。

    我在read方法后面又新增了一个read2方法,为了访问到这个方法,在路由规则后面新增了一条:

    'user/read2/:id'    => 'index/user/read2'

    也就是说,现在的路由规则最后两行是

    'user/:id'        => 'index/user/read',
    'user/read2/:id'    => 'index/user/read2',

    这样在浏览器输入http://www.mjtest.com/user/read2/3,并没有按预期去访问read2方法,实际上这个url在顺序读取路由规则时,

    先读取到'user/:id'        => 'index/user/read'这条规则,就认为url是符合这条规则的。就把read2,3当成两个参数传递给了read方法

    浏览器输入结果如图

    从图中结果可以知道,服务器实际上访问到了read方法里。

    将路由修改如下:

    route.php
    'user/read2/:id'    => 'index/user/read2',
    'user/:id'        => 'index/user/read',

    访问url:http://www.mjtest.com/user/read2/3

    访问结果:

    -----------function read2() running...-----------
    id : 3
    流年
    liunian@qq.com
    1977/03/05

    这样就正确访问到read2方法了。

  • 相关阅读:
    我的git笔记
    我的 Sublime Text 2 笔记
    在Windows系统配置Jekyll
    纯CSS3打造七巧板
    JavaScript原型之路
    基于Grunt构建一个JavaScript库
    How React Works (一)首次渲染
    hadoop2.4 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
    pyinstaller打包python源程序访问hive
    hadoop balance均衡datanode存储不起作用问题分析
  • 原文地址:https://www.cnblogs.com/flyfish919/p/6819217.html
Copyright © 2011-2022 走看看