settype()
函数在 PHP 中主要用于改变变量的类型
$str = "123";
settype($str, "integer");
echo $str; // 输出:123
$str = "123.45";
settype($str, "float");
echo $str; // 输出:123.45
$str = "true";
settype($str, "boolean");
echo $str; // 输出:1
$num = 123;
settype($num, "string");
echo $num; // 输出:"123"
$arr = array("name" => "John", "age" => 30);
settype($arr, "object");
echo $arr->name; // 输出:John
class Person {
public $name = "John";
public $age = 30;
}
$obj = new Person();
settype($obj, "array");
echo $obj["name"]; // 输出:John
注意:在使用 settype()
函数时,请确保变量的值与目标类型兼容。否则,可能会导致意外的结果或错误。