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方法了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找 php 報錯如下:Notice: Trying to get property of non-object php 報錯 Trying to get property of non-object 解決方案 Laravel 避免 Trying to get property of non-object 錯誤的六種方法 [新增第六種 data_get] Ubuntu使用——15(thinkphp路由報錯Non-static method think\Route::get() should not be called statically) Vue報錯:Uncaught TypeError: Cannot assign to read only property’exports‘ of object’#‘的解決方法 [one day one question] webpack 打包報錯 Cannot assign to read only property 'exports' of object '#' vue運行報錯error:Cannot assign to read only property 'exports' of object '#' Django | 模型類變更后生成遷移文件,報錯:You are trying to add a non-nullable field 'BookName' to BookInfo without a default.... Sqoop報錯Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction myqltransactionRollbackexception deadlock found when trying to get lock
 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM