note 71899 added to language.types.integer
| From: | popefelix at gmail dot com | Date: | Thu, 21 Dec 2006 14:50:16 +0000 |
| Subject: | note 71899 added to language.types.integer | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-120830@lists.php.net to get a copy of this message | ||
Be careful when using integer conversion to test something to see if it evaluates to a positive
integer or not. You might get unexpected behaviour.
To wit:
<?php
error_reporting(E_ALL);
require_once 'Date.php';
$date = new Date();
print "\$date is an instance of " . get_class($date) . "\n";
$date += 0;
print "\$date is now $date\n";
var_dump($date);
$foo = new foo();
print "\$foo is an instance of " . get_class($foo) . "\n";
$foo += 0;
print "\$foo is now $foo\n";
var_dump($foo);
class foo {
var $bar = 0;
var $baz = "la lal la";
var $bak;
function foo() {
$bak = 3.14159;
}
}
?>
After the integer conversion, you might expect both $foo and $date to evaluate to 0. However, this
is not the case:
$date is an instance of Date
Notice: Object of class Date could not be converted to int in
/home/kpeters/work/sketches/ObjectSketch.php on line 7
$date is now 1
int(1)
$foo is an instance of foo
Notice: Object of class foo could not be converted to int in
/home/kpeters/work/sketches/ObjectSketch.php on line 13
$foo is now 1
int(1)
This is because the objects are first converted to boolean before being converted to int.
----
Server IP: 64.71.164.2
Probable Submitter: 68.58.250.171
----
Manual Page -- http://www.php.net/manual/en/language.types.integer.php
Edit -- https://master.php.net/note/edit/71899
Del: integrated -- https://master.php.net/note/delete/71899/integrated
Del: useless -- https://master.php.net/note/delete/71899/useless
Del: bad code -- https://master.php.net/note/delete/71899/bad+code
Del: spam -- https://master.php.net/note/delete/71899/spam
Del: non-english -- https://master.php.net/note/delete/71899/non-english
Del: in docs -- https://master.php.net/note/delete/71899/in+docs
Del: other reasons-- https://master.php.net/note/delete/71899
Reject -- https://master.php.net/note/reject/71899
Search -- https://master.php.net/manage/user-notes.php