【问题标题】:Type casting using string for type使用字符串进行类型转换
【发布时间】:2017-08-25 16:32:24
【问题描述】:

我有表 settings 与列: value - varchar 类型包含设置值,type - 枚举类型包含变量类型 "int", "string", "float"。如何使用type 列中的字符串将值转换为这种类型?

我正在尝试在我的模型中这样做,但它不起作用:

public function getValueAttribute($value){
    return ($this->type)$value;
}

【问题讨论】:

  • 考虑改用settype()

标签: php laravel-5 typecast-operator


【解决方案1】:

你必须使用settype()函数:

<?php 

$var = 42;
var_dump($var);  //  int 42
$type = 'string';
settype($var, $type);
var_dump($var);  //  string '42'

适应你的代码 sn-p :

public function getValueAttribute($value){
    settype($value, $this->type);
    return $value;
}

【讨论】:

    【解决方案2】:

    您不能使用这样的动态类型转换,而是必须为此使用函数。 settype() 接受两个参数,即原始值和您要将其类型转换为的新类型。

    public function getValueAttribute($value){
        settype($value, $this->type);
        return $value;
    }
    

    【讨论】:

    • 您正在返回settype() 的结果,它始终是bool。您需要返回 $value ;)
    • 您知道,我在您发表评论时按下了编辑 ;-) 但是为指出这一点而欢呼! ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多