PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Variáveis> <Tipos
Last updated: Fri, 22 Aug 2008

view this page in

Manipulação de tipos

O PHP não requer (ou suporta) a definição de tipo explícita na declaração de variáveis: o tipo de uma variável é determinado pelo contexto em que a variável é utilizada. Isto significa que, se você atribuir um valor string para a variável $var , $var se torna uma string. Se você então atribuir um valor inteiro para $var , ela se torna um inteiro.

Um exemplo da conversão automática do PHP é o operador de adição '+'. Se qualquer um dos operadores for float, então todos os operadores são avaliados como floats, e o resultado será um float. De outra forma, se os operadores forem interpretados como integers então o resultado será um integer. Note que isso não muda os tipos dos operadores: apenas muda em como esses operadores são avaliados.

<?php
$foo 
"0";  // $foo é string (ASCII 48)
$foo += 2;   // $foo é agora um interio (2)
$foo $foo 1.3;  // $foo é agora um float (3.3)
$foo "10 pequenos porcos";   // $foo é inteiro (15)
$foo "10 minúsculos porcos"// $foo é inteiro (15)
?>

Se os últimos dois exemplos lhe parecerem estranhos, veja Conversão de strings para números.

Para forçar uma variável para ser avaliada como um certo tipo, veja a seção Moldando o tipo (casting). Se você deseja mudar o tipo de uma variável, veja settype().

Para testar qualquer um dos exemplo desta seção, você pode usar a função var_dump().

Nota: O comportamento de uma conversão automática para array é atualmente indefinida.
Também, pelo PHP suporta indexação em strings via índice usando a mesma sintaxe de array, o seguinte exemplo é válido para todas versões do PHP:

<?php
$a    
'car'// $a é uma string
$a[0] = 'b';   // $a é ainda uma string
echo $a;       // bar
?>
Veja a seção entitulada Acessando caracteres da string para mais informações.

Conversão de Tipos - Type Casting

A conversão de tipos no PHP funciona como no C: o nome de um tipo desejado é escrito entre parênteses antes da variável em que se deseja a moldagem.

<?php
$foo 
10;             // $foo é um inteiro
$bar = (boolean) $foo// $bar é um booleano
?>

As moldagens permitidas são:

  • (int), (integer) - molde para inteiro
  • (bool), (boolean) - converte para booleano
  • (float), (double), (real) - converte para número de ponto flutuante
  • (string) - converte para string
  • (binary) - converte para string binária (PHP 6)
  • (array) - converte para array
  • (object) - converte para objeto
  • (unset) - converte para NULL (PHP 5)

(binary) e o prefixo b é foram adicionados no PHP 5.2.1

Note que tabulações e espaços são permitidos dentro dos parênteses, então o seguinte são funcionalmente equivalentes:

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

Convertendo uma string literal e variáveis para strings binárias:

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

Nota: Em vez de converter uma variável para string, você também pode englobar a variável entre aspas duplas.

<?php
$foo 
10;            // $foo é um interio
$str "$foo";        // $str é uma string
$fst = (string) $foo// $fst tambem é uma string

// Isto imprimirah "eles são o mesmo"
if ($fst === $str) {
    echo 
"eles são o mesmo";
}
?>

Pode não ser tão óbvio o que exatamente ocorre quando se converte entre certos tipos. Para mais informações, veja essas seções:



Variáveis> <Tipos
Last updated: Fri, 22 Aug 2008
 
add a note add a note User Contributed Notes
Manipulação de tipos
kjarli at gmail dot com
30-Jul-2008 06:58
@alexgr at gmail dot com

Your code will not cast.
By entering (MyObject $myObject), you only force $myObject to be an instanceof $myObject as a parameter.
alexgr at gmail dot com
20-Jun-2008 06:43
For a Cast to a User Defined Object you can define a cast method:

class MyObject {
    /**
     * @param MyObject $object
     * @return MyObject
     */
    static public function cast(MyObject $object) {
        return $object;
    }
}

In your php page code you can:
$myObject = MyObject::cast($_SESSION["myObject"]);

Then, PHP will validate the value and your IDE will help you.
miracle at 1oo-percent dot de
20-Feb-2006 09:26
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)
23-Jun-2005 08:47
If you have a boolean, performing increments on it won't do anything despite it being 1.  This is a case where you have to use a cast.

<html>
<body> <!-- don't want w3.org to get mad... -->
<?php
$bar
= TRUE;
?>
I have <?=$bar?> bar.
<?php
$bar
++;
?>
I now have <?=$bar?> bar.
<?php
$bar
= (int) $bar;
$bar++;
?>
I finally have <?=$bar?> bar.
</body>
</html>

That will print

I have 1 bar.
I now have 1 bar.
I finally have 2 bar.
toma at smartsemantics dot com
10-Mar-2005 10:24
In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes.  It also makes use of some regular expression matching rather than string position, replacing, etc.  It takes an object ($obj) of any type and casts it to an new type ($class_type).  Note that the new class type must exist:

function ClassTypeCast(&$obj,$class_type){
    if(class_exists($class_type,true)){
        $obj = unserialize(preg_replace"/^O:[0-9]+:\"[^\"]+\":/i",
          "O:".strlen($class_type).":\"".$class_type."\":", serialize($obj)));
    }
}
Raja
10-Feb-2005 07:05
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
tom5025_ at hotmail dot com
25-Aug-2004 04:27
function strhex($string)
{
   $hex="";
   for ($i=0;$i<strlen($string);$i++)
       $hex.=dechex(ord($string[$i]));
   return $hex;
}
function hexstr($hex)
{
   $string="";
   for ($i=0;$i<strlen($hex)-1;$i+=2)
       $string.=chr(hexdec($hex[$i].$hex[$i+1]));
   return $string;
}

to convert hex to str and vice versa
dimo dot vanchev at bianor dot com
10-Mar-2004 11:02
For some reason the code-fix posted by philip_snyder at hotmail dot com [27-Feb-2004 02:08]
didn't work for me neither with long_class_names nor with short_class_names. I'm using PHP v4.3.5 for Linux.
Anyway here's what I wrote to solve the long_named_classes problem:

<?php
function typecast($old_object, $new_classname) {
    if(
class_exists($new_classname)) {
       
$old_serialized_object = serialize($old_object);
       
$old_object_name_length = strlen(get_class($old_object));
       
$subtring_offset = $old_object_name_length + strlen($old_object_name_length) + 6;
       
$new_serialized_object  = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":';
       
$new_serialized_object .= substr($old_serialized_object, $subtring_offset);
        return
unserialize($new_serialized_object);
     } else {
         return
false;
     }
}
?>
philip_snyder at hotmail dot com
27-Feb-2004 11:08
Re: the typecasting between classes post below... fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem... SO here's a simple fix:

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    // Example serialized object segment
    // O:5:"field":9:{s:5:...   <--- Class: Field
    $old_serialized_prefix  = "O:".strlen(get_class($old_object));
    $old_serialized_prefix .= ":\"".get_class($old_object)."\":";

    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:'.strlen($new_classname).':"'.$new_classname . '":';
    $new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
   return unserialize($new_serialized_object);
  }
  else
   return false;
}

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. ;)
post_at_henribeige_dot_de
04-May-2003 12:37
If you want to do not only typecasting between basic data types but between classes, try this function. It converts any class into another. All variables that equal name in both classes will be copied.

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' .
                             substr($old_serialized_object, $old_serialized_object[2] + 7);
    return unserialize($new_serialized_object);
  }
  else
    return false;
}

Example:

class A {
  var $secret;
  function A($secret) {$this->secret = $secret;}
  function output() {echo("Secret class A: " . $this->secret);}
}

class B extends A {
  var $secret;
  function output() {echo("Secret class B: " . strrev($this->secret));}
}

$a = new A("Paranoia");
$b = typecast($a, "B");

$a->output();
$b->output();
echo("Classname \$a: " . get_class($a) . "Classname \$b: " . get_class($b));

Output of the example code above:

Secret class A: Paranoia
Secret class B: aionaraP
Classname $a: a
Classname $b: b
yury at krasu dot ru
27-Nov-2002 05:24
incremental operator ("++") doesn't make type conversion from boolean to int, and if an variable is boolean and equals TRUE than after ++ operation it remains as TRUE, so:

$a = TRUE;
echo ($a++).$a;  // prints "11"
29-Aug-2002 01:26
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!

Variáveis> <Tipos
Last updated: Fri, 22 Aug 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites