CKTIS / PHP
settype()
Convierte la propia variable según el nombre del tipo.
Versión: PHP 8.4; repository runtime, production runtime not attested
Sintaxis
settype(mixed &$var, string $type): boolConvierte la propia variable según el nombre del tipo. El booleano devuelto indica el éxito y el valor convertido queda en el primer argumento. En PHP 8 un nombre de tipo desconocido provoca ValueError.
Firma
settype(mixed &$var, string $type): bool
Salida del ejemplo
[true,12,"int"]
ValueError
Ejemplos
<?php
$quantity = "12";
$ok = settype($quantity, "int");
echo json_encode([$ok, $quantity, get_debug_type($quantity)]), PHP_EOL;
try { settype($quantity, "decimal"); } catch (ValueError $e) { echo "ValueError"; }
Resultado
[true,12,"int"] ValueError