PHP 8.3.4 Released!

Manipulación de tipos

PHP no requiere (ni soporta) la definición explicita de tipos en la declaración de variables; el tipo de la variable se determina por el contexto en el cual se emplea la variable. Es decir, si se asigna un valor string a una variable $var, entonces $var se convierte en un string. Si un valor integer es entonces asignado a la misma variable $var, ésta se convierte en integer.

Un ejemplo de la conversión de tipos automática de PHP es el operador suma '+'. Si al menos uno de los operandos es float, entonces ambos operandos son evaluados como floats y el resultado será un float. De otra manera, los operandos seran interpretados como integers, y el resultado será entonces integer. Tenga en cuenta que esto no implica que se cambien los tipos de los propios operandos; el único cambio es en como se evalúan los operandos y en el tipo de expresión en sí mismo.

<?php
$foo
= "0"; // $foo es string (ASCII 48)
$foo += 2; // $foo es ahora un integer (2)
$foo = $foo + 1.3; // $foo es ahora un float (3.3)
$foo = 5 + "10 Cerditos pequeñitos"; // $foo es integer (15)
$foo = 5 + "10 Cerdos pequeños"; // $foo es integer (15)
?>

Si considera confusos los últimos dos ejemplos anteriores, consulte Conversión de cadenas a números.

Para forzar a que una variable sea evaluada como un determinado tipo, consulte la sección Forzado de tipos. Para cambiar el tipo de variable, consulte la función settype().

Para probar cualquiera de los ejemplos de esta sección, utilice la función var_dump().

Nota:

El comportamiento de la conversión automática en array está actualmente sin definir.

Tambien, debido a que PHP soporta el indexado de string mediante compensaciones mediante la misma sintaxis empleada en el indexado de arrays, los siguientes ejemplos son válidos para todas las versiones de PHP:

<?php
$a
= 'car'; // $a es un string
$a[0] = 'b'; // $a sigue siendo un string
echo $a; // bar
?>

Consulte la sección Acceso a cadenas mediante caracteres para más información.

Forzado de tipos

El forzado de tipos en PHP funciona de la misma manera que en C:, donde el nombre del tipo deseado se escribe entre paréntesis antes de la variable que se quiera forzar.

<?php
$foo
= 10; // $foo es un integer
$bar = (boolean) $foo; // $bar es un boolean
?>

Los siguientes forzados de tipos están permitidos:

  • (int), (integer) - forzado a integer
  • (bool), (boolean) - forzado a boolean
  • (float), (double), (real) - forzado a float
  • (string) - forzado a string
  • (array) - forzado a array
  • (object) - forzado a object
  • (unset) - forzado a NULL (PHP 5)

El forzado (binary) y el soporte del prefijo b fueron añadidos en PHP 5.2.1

Fíjese que se permiten las tabulaciones y espacios dentro de los paréntesis, por lo que los siguientes ejemplos son funcionalmente equivalentes:

<?php
$foo
= (int) $bar;
$foo = ( int ) $bar;
?>

Forzado literal de strings y variables a strings binarios:

<?php
$binary
= (binary) $string;
$binary = b"binary string";
?>

Nota:

El lugar de forzar una variable a string, tambien se puede encerrar la variable entre comillas dobles.

<?php
$foo
= 10; // $foo es un integer
$str = "$foo"; // $str es un string
$fst = (string) $foo; // $fst es tambien un string

// Esto muestra que "son lo mismo"
if ($fst === $str) {
echo
"son lo mismo";
}
?>

Puede que no sea obvio que sucede exactamente cuando se fuerzan ciertos tipos. Para más información, consulte estas secciones:

add a note

User Contributed Notes 7 notes

up
66
Raja
19 years ago
Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example):

$dividend = 2;
$divisor = 3;
$quotient = $dividend/$divisor;
print $quotient; // 0.66666666666667
up
27
fardelian
10 years ago
Casting objects to arrays is a pain. Example:

<?php

class MyClass {

private
$priv = 'priv_value';
protected
$prot = 'prot_value';
public
$pub = 'pub_value';
public
$MyClasspriv = 'second_pub_value';

}

$test = new MyClass();
echo
'<pre>';
print_r((array) $test);

/*
Array
(
[MyClasspriv] => priv_value
[*prot] => prot_value
[pub] => pub_value
[MyClasspriv] => second_pub_value
)
*/

?>

Yes, that looks like an array with two keys with the same name and it looks like the protected field was prepended with an asterisk. But that's not true:

<?php

foreach ((array) $test as $key => $value) {
$len = strlen($key);
echo
"{$key} ({$len}) => {$value}<br />";
for (
$i = 0; $i < $len; ++$i) {
echo
ord($key[$i]) . ' ';
}
echo
'<hr />';
}

/*
MyClasspriv (13) => priv_value
0 77 121 67 108 97 115 115 0 112 114 105 118
*prot (7) => prot_value
0 42 0 112 114 111 116
pub (3) => pub_value
112 117 98
MyClasspriv (11) => second_pub_value
77 121 67 108 97 115 115 112 114 105 118
*/

?>

The char codes show that the protected keys are prepended with '\0*\0' and private keys are prepended with '\0'.__CLASS__.'\0' so be careful when playing around with this.
up
12
Anonymous
3 years ago
Cast operators have a very high precedence, for example (int)$a/$b is evaluated as ((int)$a)/$b, not as (int)($a/$b) [which would be like intdiv($a,$b) if both $a and $b are integers].
The only exceptions (as of PHP 8.0) are the exponentiation operator ** [i.e. (int)$a**$b is evaluated as (int)($a**$b) rather than ((int)$a)**$b] and the special access/invocation operators ->, ::, [] and () [i.e. in each of (int)$a->$b, (int)$a::$b, (int)$a[$b] and (int)$a($b), the cast is performed last on the result of the variable expression].
up
11
miracle at 1oo-percent dot de
18 years ago
If you want to convert a string automatically to float or integer (e.g. "0.234" to float and "123" to int), simply add 0 to the string - PHP will do the rest.

e.g.

$val = 0 + "1.234";
(type of $val is float now)

$val = 0 + "123";
(type of $val is integer now)
up
11
rmirabelle
13 years ago
The object casting methods presented here do not take into account the class hierarchy of the class you're trying to cast your object into.

/**
* Convert an object to a specific class.
* @param object $object
* @param string $class_name The class to cast the object to
* @return object
*/
public static function cast($object, $class_name) {
if($object === false) return false;
if(class_exists($class_name)) {
$ser_object = serialize($object);
$obj_name_len = strlen(get_class($object));
$start = $obj_name_len + strlen($obj_name_len) + 6;
$new_object = 'O:' . strlen($class_name) . ':"' . $class_name . '":';
$new_object .= substr($ser_object, $start);
$new_object = unserialize($new_object);
/**
* The new object is of the correct type but
* is not fully initialized throughout its graph.
* To get the full object graph (including parent
* class data, we need to create a new instance of
* the specified class and then assign the new
* properties to it.
*/
$graph = new $class_name;
foreach($new_object as $prop => $val) {
$graph->$prop = $val;
}
return $graph;
} else {
throw new CoreException(false, "could not find class $class_name for casting in DB::cast");
return false;
}
}
up
16
Anonymous
21 years ago
Printing or echoing a FALSE boolean value or a NULL value results in an empty string:
(string)TRUE //returns "1"
(string)FALSE //returns ""
echo TRUE; //prints "1"
echo FALSE; //prints nothing!
up
14
ieee at REMOVE dot bk dot ru
11 years ago
There are some shorter and faster (at least on my machine) ways to perform a type cast.
<?php
$string
='12345.678';
$float=+$string;
$integer=0|$string;
$boolean=!!$string;
?>
To Top