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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵