1

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;' );

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It works perfectly. To my shame I was unable to make up a correct search query to find this function.
That's great! You're welcome. I would've searched something like "dynamic type casting".
1

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)

1 Comment

Great solution, however (IMHO) settype() is far more convenient, because the name of function tells what it does. Clear code == good code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.