Trying to get property of non-object_thinkphp路由報錯

來源:互聯網
上載者:User

標籤:路由規則   trying   流年   title   cat   erro   cep   index   blog   

在閱讀《thinkphp5.0快速入門》這本書時,模型基礎這一節碰到一點路由上的問題。在此隨筆記一下。

碰到的問題:

[8] ErrorException in UserController.php line 43Trying 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
流年
[email protected]
1977/03/05

這樣就正確訪問到read2方法了。

Trying to get property of non-object_thinkphp路由報錯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.