Search code examples
phplaravel-5typecast-operator

Type casting using string for type


I have table settings with columns: value - varchar type contains setting value and type - enum type contains variable types "int", "string", "float". How can I use string from type column to cast value to this type?

I'm trying to do it in my model but it doesn't work:

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

Solution

  • You have to use the settype() function :

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

    Adapted to your code snippet :

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