douchen5971 2014-05-25 16:24
浏览 67
已采纳

类名作为公共函数中的参数

What's the difference between:

class PostController extends \BaseController {
      public function delete($id) {
        $deletePost = Post::findOrFail($id);
        return View::make('backend.delete')->with('post', $deletePost);
      }
}

and

class PostController extends \BaseController {
      public function delete(Post $post) {
        return View::make('backend.delete')->with('post', $post);
      }
}

Can somebody explain to me: public function delete(Post $post)

we are taking a Class named "Post" as a variable $post?

UPDATE1.

in routes.php:

Route::model('post', 'Post');

Route::get('delete/{post}', array('uses' => 'PostController@delete'));
Route::post('delete', array('uses' => 'PostController@doDelete'));

and in PostController.php:

public function delete(Post $post) {
    return View::make('backend.delete')->with('post', $post);
}

public function doDelete() {
    $post = Post::findOrFail(Input::get('id'));
    $post->delete();

    return Redirect::action('PostController@home');
}

but anyway i get an error: No query results for model [Post]. with the 2nd method.

  • 写回答

2条回答 默认 最新

  • duanjianxiu9400 2014-05-25 17:50
    关注

    It's just a type hinting:

    "Type hinting means that whatever you pass must be an instance of (the same type as) the type you're hinting."

    In your example it's Post:

    public function delete(Post $post) { /* code */ }
    

    It's just checks $post variable whether instance it or not. So everything looks good in your code. And it should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题
  • ¥20 基于matlab的航迹融合 航迹关联 航迹插补