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

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)