将 class 变量设置为具有相同名称的关联数组键?
Set class variables to associative array keys with same name?
我正在使用 Laravel 制作网站。我有一个 Model
的帖子。我有一个静态方法 getPost
,它应该使用 table posts
.
中的关联列数组创建我的 Post
模型的新实例
我想在 Post
模型 class 中使用与 table.
中的列同名的相应变量
即
Posts:
_________________________________________________
| id | title | ...etc | |
|-------------------------------------------------|
| 1 | This | | |
|-------------------------------------------------|
| 2 | That | | |
然后在我的 class:
<?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);
}
}
因此,正如我所说,我希望 class 中的变量与关联数组中的键同名,以便自动设置为它们的值。我目前不知道有什么办法可以做到这一点。如果需要,我可以在构造函数中手动设置它们,但我很好奇是否有更简单、更轻松的方法来做到这一点?喜欢某种功能或其他什么。
感谢您的帮助或建议!
你试过吗?
foreach($data as $key => $value) {
$this->$key = $value;
}
我正在使用 Laravel 制作网站。我有一个 Model
的帖子。我有一个静态方法 getPost
,它应该使用 table posts
.
Post
模型的新实例
我想在 Post
模型 class 中使用与 table.
即
Posts:
_________________________________________________
| id | title | ...etc | |
|-------------------------------------------------|
| 1 | This | | |
|-------------------------------------------------|
| 2 | That | | |
然后在我的 class:
<?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);
}
}
因此,正如我所说,我希望 class 中的变量与关联数组中的键同名,以便自动设置为它们的值。我目前不知道有什么办法可以做到这一点。如果需要,我可以在构造函数中手动设置它们,但我很好奇是否有更简单、更轻松的方法来做到这一点?喜欢某种功能或其他什么。
感谢您的帮助或建议!
你试过吗?
foreach($data as $key => $value) {
$this->$key = $value;
}