有没有办法从字符串中创建一个对象内部的变量?例如:
class Whatever {
public function createVariables() {
$this["variable_name"] = 100;
}
}我希望根据子类定义的一组规则动态创建变量。
发布于 2017-01-28 05:43:02
class Whatever {
public function createAttributes($attribute_name, $attribute_value = NULL) {
$this->{$attribute_name} = $attribute_value;
}
}这是PHP中动态添加属性的方法,与laravel没有特别的关系
Laravel也有一个内置的https://github.com/illuminate/database/blob/v4.2.17/Eloquent/Model.php#L2551方法
发布于 2017-01-28 05:48:08
class Whatever {
protected $id;
public function createAttributes($id) {
$this->id = $id;
return $this;
}
}您可以在另一个函数中以$this->id的形式调用此变量
https://stackoverflow.com/questions/41903397
复制相似问题