dongxing2302
2019-06-07 07:34
浏览 70
已采纳

MVC路由,将数组作为参数传递(Laravel / CodeIgniter样式)

I am going over a PHP / MVC / OOP course by Traversy Media and I am on a chapter that creates a router for a simple social app (initial routing of any request throguh domain.com/index.php).

The person talks about passing an array as a parameter and I don't get how this works:

class Posts {
   public function edit($id) {
      $post = $this->postModel->fetchPost($id); 
      $this->view('edit', ['post' => $post]);
  }
}

There is some more simple things in this class but I am just not sure about the ['post' => $post] part.

I don't get how this syntax works, like sign after sign. Is this based on something that is already builed in into some kind of framework (he does not have anything like this here, this is his and this is the first chapter when he builds it from scratch). I mean, I would imagine that array would be like an $array, in a variable and this is a parameter in square brackets, so what is the name of the array here?

Is this $post and is the second actual => $post a sub-array. I just dont get that at all.

I started learning Laravel previously (skipping this all together for now) and I've been getting stuck on such things too.

I mean, is this like framework-related only (not really a regular procedural PHP), like something that is already coded on a deeper level and we relate to that?

Thank you in advance for any info that I could get.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanke0178 2019-06-07 08:20
    已采纳

    The part you are confused about is just a function call.

    $this-view('edit',['post' => $post]);
    

    This could have been written like this

    $dataYouWantToPassToTheView = ['post' => $post];
    
    $this->view('edit', $dataYouWantToPassToTheView);
    

    You are calling the function view, and passing it two parameters. An Edit String and an Array containing a key post with a value of a variable called post. The view function simply takes all the values in the array and makes them available by their keys in the view.

    This means you can in the view do the following

    <span>This is post id: {{ $post->id }}</span>
    

    Passing an Array as a parameter is regular PHP and has nothing to do with the specific framework. The Array doesn't need a "name", just like the 'edit' String doesn't need a name.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题