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()
函數時,請確保變量的值與目標類型兼容。否則,可能會導致意外的結果或錯誤。