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

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

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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算