将类变量设置为具有相同名称的关联数组键吗?

时间:2018-12-05 22:54:40

标签: php class associative-array laravel-5.7

我正在使用Laravel建立一个网站。我有Model个帖子。我有一个静态方法getPost,应该使用表Post中列的关联数组为我的posts模型创建新实例。

我想在Post模型类中具有与表中各列同名的相应变量。

Posts:
 _________________________________________________
|  id  |  title  | ...etc |                       |
|-------------------------------------------------|
|  1   |  This   |        |                       |
|-------------------------------------------------|
|  2   |  That   |        |                       |

然后在我的课上:

<?php

class Post extends Model
{
    public $id, $title;

    public function __construct(array $attributes = [], $data = null)
    {
        parent::__construct($attributes);

        if(!is_object($data)) return;

        /*Set $this->title = $data->title, $this->id = $data->id
          Except a quicker way to set variables of the same name to
          the corresponding key in the array without having to do the above
          for every single variable, which will become a problem as the
          the table grows and holds more data which is what I anticipate.*/
    }

    static public function getPost($id)
    {
        $temp = new Post();
        $post = DB::table($temp->getTable())->where('id', $id)->first();

        return new Post([], $post);
    }
}

因此,正如我所说,我希望类中的变量与关联数组中的键具有相同的名称,以自动将其设置为它们的值。我目前不知道有什么办法。如果需要的话,我可以在构造函数中手动设置它们,但我只是好奇是否有一种更简单,更轻松的方法呢?喜欢某种功能或不喜欢什么。

感谢您的帮助或建议!

1 个答案:

答案 0 :(得分:1)

您尝试过吗?

foreach($data as $key => $value) {
    $this->$key = $value;
}