haldagan
haldagan

Reputation: 911

Is it possible in php to turn string var into type name?

So, can I get this code working:

    $typename='integer';
    $tmp='12321321312';
    $var=($typename)$tmp;

WITHOUT using conditions, like:

    if($typename=='integer')
        $var=(integer) $tmp;

AND WITHOUT using evals, like:

   eval( '$var=(' . $typename . ') $tmp;' );

Upvotes: 1

Views: 160

Answers (2)

swatkins
swatkins

Reputation: 13640

You can use settype.

$typename = 'integer';
$tmp = '12321321312'; // $tmp will be passed as a reference
settype($tmp, $typename);

// $tmp is now an integer

Possibles values of type are:

  • "boolean" (or, since PHP 4.2.0, "bool")
  • "integer" (or, since PHP 4.2.0, "int")
  • "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double")
  • "string"
  • "array"
  • "object"
  • "null" (since PHP 4.2.0)

Upvotes: 2

Amal
Amal

Reputation: 76666

Yes, it is possible using anonymous functions (available on PHP versions => 5.3.0).

$typename = 'intval';
$tmp = '2323';
$var = $typename($tmp); // <= note the syntax difference
var_dump($var);

Output:

int(2323)

Upvotes: 1

Related Questions