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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化