namaroulis stated "I found it tricky to check if a posted value was an integer"; to test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric():
<?php
$_POST['a'] = "42";
is_numeric( $_POST['a'] ); // true
?>
Manipulation des types
PHP n'impose pas de définir explicitement le type d'une variable lors de sa déclaration ; le type d'une variable est déterminé par son contexte d'utilisation. Si une valeur de type string est assignée à la variable $var, $var devient de type string. Si une valeur de type integer est ensuite assignée à cette variable $var, alors, son type devient integer.
Un exemple de conversion de type automatique avec PHP est l'ajout de l'opérateur '+'. Si une des opérandes est de type float, alors toutes les opérandes seront évaluées comme de types float, et le résultat sera de type float. Sinon, les opérandes seront interprétées comme integers, et le résultat sera également de type integer. Noter que cela ne modifie pas le type des opérandes ; la seule modification est la façon dont les opérandes sont évaluées et le type de l'expression elle-même.
<?php
$foo = "0"; // $foo est une chaîne de caractères (ASCII 48)
$foo += 2; // $foo est maintenant un entier (2)
$foo = $foo + 1.3; // $foo est maintenant un nombre à virgule flottante (3.3)
$foo = 5 + "10 Little Piggies"; // $foo est un entier (15)
$foo = 5 + "10 Small Pigs"; // $foo est un entier (15)
?>
Si les 2 derniers exemples vous semblent compliqués, reportez-vous à la section sur les conversions de chaînes en nombres.
Pour forcer une variable à être évaluée en un certain type, reportez-vous à la section sur le transtypage. Pour changer le type d'une variable, reportez-vous à la fonction settype().
Pour tester les exemples de cette section, utilisez la fonction var_dump().
Note:
Le comportement d'une conversion automatique en tableau est actuellement non-défini.
De plus, vu que PHP supporte l'indexation des chaînes de caractères via des positions en utilisant la même syntaxe que pour les tableaux, l'exemple suivant est correct pour toutes les versions de PHP :
<?php
$a = 'car'; // $a est une chaîne de caractères
$a[0] = 'b'; // $a est toujours une chaîne de caractères
echo $a; // bar
?>Reportez-vous à la section sur l'accès aux chaînes par ces caractères pour plus d'informations.
Modification de types
La modification de types en PHP fonctionne de la même façon qu'en C : le nom du type désiré est écrit entre parenthèses avant la variable à traiter.
<?php
$foo = 10; // $foo est un entier
$bar = (boolean) $foo; // $bar est un booléen
?>
Les préfixes autorisés sont :
- (int), (integer) : modification en integer
- (bool), (boolean) : modification en boolean
- (float), (double), (real) : modification en float
- (string) : modification en string
- (array) : modification en array
- (object) : modification en object
- (unset) : modification en NULL (PHP 5)
La modification en binaire et le préfixe b ont été ajoutés en PHP 5.2.1
Notez que les tabulations et les espaces sont autorisés dans les parenthèses. Les exemples suivants sont fonctionnellement équivalents :
<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>
Modification d'une chaîne littérale et de variables en chaînes binaires :
<?php
$binary = (binary) $string;
$binary = b"binary string";
?>
Note:
Au lieu de modifier une variable en chaîne, il est également possible d'entourer la variable de doubles guillemets.
<?php
$foo = 10; // $foo est un entier
$str = "$foo"; // $str est une chaîne
$fst = (string) $foo; // $fst est également une chaîne
// Ceci affichera "ils sont identiques"
if ($fst === $str) {
echo "ils sont identiques";
}
?>
Le comportement d'une modification de type n'est pas toujours identique suivant les types. Pour plus d'informations, reportez-vous à ces sections :
Cast a string to binary using PHP < 5.2.1
$binary = unpack('c*', $string);
Type casting from string to int and vice versa is probably the most common conversation. PHP does this very simply through the +. and .= operators, removing any explicit casting:
<?php
$x = 1;
var_dump($x); // int(1)
$x .= 1;
var_dump($x); // string(2) "11"; also an empty string ("") would cast to string without changing $x
$x = "1";
var_dump($x); // string(1) "1"
$x += 1;
var_dump($x); // int(2); also a zero value (0) would cast to int without changing $x
?>
Checking for strings to be integers?
How about if a string is a float?
<?php
/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt=preg_match('/^\s*([0-9]+)\s*$/', $myString, $myInt);
echo 'Is Integer? ', ($isInt) ? 'Yes: '.$myInt[1] : 'No', "\n";
/* checks if a string is an integer with no whitespace before or after */
$isInt=preg_match('/^[0-9]+$/', $myString);
echo 'Is Integer? ', ($isInt) ? 'Yes' : 'No', "\n";
/* When checking for floats, we assume the possibility of no decimals needed. If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
[0-9]+(\.[0-9]+)?
with
[0-9]+\.[0-9]+
*/
/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat=preg_match('/^\s*([0-9]+(\.[0-9]+)?)\s*$/', $myString, $myNum);
echo 'Is Number? ', ($isFloat) ? 'Yes: '.$myNum[1] : 'No', "\n";
/* checks if a string is a float with no whitespace before or after */
$isInt=preg_match('/^[0-9]+(\.[0-9]+)?$/', $myString);
echo 'Is Number? ', ($isFloat) ? 'Yes' : 'No', "\n";
?>
I found it tricky to check if a posted value was an integer.
<?php
$_POST['a'] = "42";
is_int( $_POST['a'] ); //false
is_int( intval( "anything" ) ); //always true
?>
A method I use for checking if a string represents an integer value.
<?php
function check_int( $str )
{
return is_numeric( $str ) && intval( $str ) - $str == 0;
}
?>
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;
}
}
in response to bhsmither at gmail.com
It raises a warning because of the bad enquoted variable
<?php
error_reporting( E_ALL | E_STRICT );
$foo['ten'] = 10; // $foo['ten'] is an array holding an integer at key "ten"
$str = "{$foo['ten']}"; // works "10"
$str = "$foo[ten]"; // DO NOT work!
<?php
$foo['ten'] = 10; // $foo['ten'] is an array holding an integer at key "ten"
$str = "$foo['ten']"; // throws T_ENCAPSED_AND_WHITESPACE error
$str = "$foo[ten]"; // works because constants are skipped in quotes
$fst = (string) $foo['ten']; // works with clear intention
?>
Here is something that was a not obvious bug in my code.
Comparison statements cast string to int automatically if one of the other variable is an int.
<?php
$a=3;
$b='3d';
if ($a==$b) {
echo "a is b";
} else {
echo "a is not b";
}
?>
Result: a is b
This can cause some issues if you don't expect it
It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:
Without cast:
<?php
$hello = 'Hello world';
print $hello;
unset($hello);
?>
With the unset cast:
<?php
$hello = 'Hello world';
$hello = (unset) print $hello;
?>
Hoorah, we lost another line!
json_decode users consider this, when casting stdClass to array:
<?php
$obj = new stdClass();
$obj->{"2"} = "id";
$arr = (array) $obj;
$result = isset($arr["2"]) || array_key_exists(2, $arr); // false
?>
..though casting is at least 2x faster than foreach.
IMAGINATION REQUIRED...
We can be a witness to PHP's 'type-jugglin' in real-time with a simple implementation of a MemoryMap. For the sake our purposes, pretend that this is an empty MemoryMap.
+-------+------+------+-------+
| index | $var | type | value |
+-------+------+------+-------+
| 1 | --- | NULL | null |
| 2 | --- | NULL | null |
| 3 | --- | NULL | null |
| 4 | --- | NULL | null |
+-------+------+------+-------+
<?php
# create some variables...
$a = 10;
$b = "Hello";
$c = array(55.45, 98.65);
# Now look at map...
?>
+-------+-------+---------+--------+
| index | $var | type | value |
+-------+-------+---------+--------+
| 1 | $a | INTEGER | 10 |
| 2 | $b | STRING | Hello |
| 3 | $c[0] | FLOAT | 55.45 |
| 4 | $c[1] | FLOAT | 98.65 |
+-------+-------+---------+--------+
<?php
# Now, change the variable types...
$a = "Bye";
$b = 2;
$c[0] = "Buy";
$c[1] = "Now!";
#Look at map...
?>
+-------+-------+---------+--------+
| index | $var | type | value |
+-------+-------+---------+--------+
| 1 | $a | STRING | Bye | <- used to be INTEGER
| 2 | $b | INTEGER | 2 | <- used to be STRING
| 3 | $c[0] | STRING | Buy | <- used to be FLOAT
| 4 | $c[1] | STRING | Right | <- used to be FLOAT
+-------+-------+---------+--------+
The behavior of comparisons between objects of different types is, in fact, already documented (though a cross-reference from this page might be handy for future readers):
http://www.php.net/manual/en/language.operators.comparison.php
It would be useful to know the precedence (for lack of a better word) for type juggling. This entry currently explains that "if either operand is a float, then both operands are evaluated as floats, and the result will be a float" but could (and I think should) provide a hierarchy that indicates, for instance, "between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins" and so on (and don't count on my example accurately capturing the true hierarchy, as I haven't actually done the tests to figure it out). Thanks!
WHERE'S THE BEEF?
Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin' less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
<?php
class Point {
protected $x, $y;
public function __construct($xVal = 0, $yVal = 0) {
$this->x = $xVal;
$this->y = $yVal;
}
public function getX() { return $this->x; }
public function getY() { return $this->y; }
}
$p = new Point(25, 35);
echo $p->getX(); // 25
echo $p->getY(); // 35
?>
Ok, now we need extra powers. PHP gives us several options:
A. We can tag on extra properties on-the-fly using everyday PHP syntax...
$p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it's on a per-instance basis, blah.
B. We can try type-casting it to a different type to access more functions...
$p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with... and just like above, this only works on a per-instance basis.
C. Do it the right way using OOP - and just extend the Point class already.
<?php
class Point3D extends Point {
protected $z; // add extra properties...
public function __construct($xVal = 0, $yVal = 0, $zVal = 0) {
parent::__construct($xVal, $yVal);
$this->z = $zVal;
}
public function getZ() { return $this->z; } // add extra functions...
}
$p3d = new Point3D(25, 35, 45); // more data, more functions, more everything...
echo $p3d->getX(); // 25
echo $p3d->getY(); // 35
echo $p3d->getZ(); // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any "single lesser object" on-the-fly, and it's way easier to do.
@alexgr (20-Jun-2008)
Correct me if I'm wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what's really happening:
<?php
class MyObject {
/**
* @param MyObject $object
* @return MyObject
*/
static public function cast(MyObject $object) {
return $object;
}
/** Does nothing */
function f() {}
}
class X extends MyObject {
/** Throws exception */
function f() { throw new exception(); }
}
$x = MyObject::cast(new X);
$x->f(); // Your IDE tells 'f() Does nothing'
?>
However, when you run the script, you will get an exception.
Just a little experiment on the (unset) type cast:
<?php
$var = 1;
$var_unset = (unset) $var;
$var_ref_unset &= (unset) $var;
var_dump($var);
var_dump($var_unset);
var_dump($var_ref_unset);
?>
output:
int(1)
NULL
int(0)
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.
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)
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.
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)));
}
}
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
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
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;
}
}
?>
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. ;)
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
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"
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!
