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 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开