我有表settings
与列: value
- VARCHAR类型包含设定值和type
- 枚举类型包含变量类型"int", "string", "float"
。如何使用type
列中的字符串将此值转换为此类型?类型转换使用字符串类型
我试图做到这一点在我的模型,但它不工作:
public function getValueAttribute($value){
return ($this->type)$value;
}
我有表settings
与列: value
- VARCHAR类型包含设定值和type
- 枚举类型包含变量类型"int", "string", "float"
。如何使用type
列中的字符串将此值转换为此类型?类型转换使用字符串类型
我试图做到这一点在我的模型,但它不工作:
public function getValueAttribute($value){
return ($this->type)$value;
}
您必须使用settype()
功能:
<?php
$var = 42;
var_dump($var); // int 42
$type = 'string';
settype($var, $type);
var_dump($var); // string '42'
适应您的代码片段:
public function getValueAttribute($value){
settype($value, $this->type);
return $value;
}
你不能使用这样的动态类型转换,而必须使用第在。 settype()
需要两个参数,即原始值和您要对其进行类型转换的新类型。
public function getValueAttribute($value){
settype($value, $this->type);
return $value;
}
考虑使用'的setType()'代替 – Qirel