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

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 请专家看看这个问题出在哪里?
  • ¥15 tensorrt 推理 yolov8框出现错误
  • ¥15 用hc 05,做蓝牙控制小车 小车只能说初始遥控方向影响,后续不能更改
  • ¥15 51单片机怎么把每次输入键值保存到数组作为我的确认键的判断条件呢
  • ¥45 easy photo不能使用,求帮助
  • ¥15 c语言字符串单词入门问题报错
  • ¥30 我现在是双非人工智能专业不知道要不要转到软件工程专业
  • ¥15 请问12脉波整流机组的外特性曲线具体是如何推导
  • ¥15 abaqus里的python算法
  • ¥100 如何在思科模拟器中进入CEF模式