PHP - 来自变量的Cast类型

时间:2015-05-14 18:08:31

标签: php casting

我问自己是否可以将字符串转换为

之前定义的另一种类型

e.g。

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

和$ bar === 5

2 个答案:

答案 0 :(得分:10)

是的,有一个内置功能:

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

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

答案 1 :(得分:0)

接受以上评论,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)