PHP - 从变量转换类型

PHP - Cast type from variable

我在问自己是否可以将字符串转换为之前定义的另一种类型

例如

$type = "int";
$foo = "5";
$bar = ($type) $foo;

$bar === 5

是的,有一个内置函数:

$type = "int";
$foo = "5";
settype($foo, $type); // $foo is now the int 5

注意settype()的return值是运算成功状态,不是转换后的变量。感谢下面的@NRVM。

文档:http://php.net/manual/en/function.settype.php

根据以上评论,setting a variable will not return the number but a boolean for the succes state

<?php
$type = "int";
$foo = "5";
$bar = settype($foo, $type);
var_dump($foo);
// bool(true) 
// $bar = 1

settype($foo, $type);
var_dump($foo);
// int(5)