问题
Can some one please tell me why I get odd results rurning the following code?
<?php
class Bank
{
var $ID;
var $balance;
var $name;
function bank($name,$id,$balance=0)
{
$this->ID=$id;
$this->balance=$balance;
$this->name=$name;
}
function getBalance()
{
return $this->balance;
}
function setBalance($bal)
{
$this->balance=$bal;
}
function getId()
{
return $this->ID;
}
function setId($i)
{
$this->ID=$i;
}
)
$b= new bank(yaniv,027447002, 15000);
Now when I try to echo:
$b->ID
Instead of the expected 027447002 I get an odd 6180354, but if I initiate the object like this :
$b=new bank(yaniv,'027447002',15000);
(notice I quoted the id property) it works OK. Any suggestion why is this happening and what is the right way to fix it?
回答1:
027447002 is in octal, as it prefixed with a zero. Convert that to decimal and you get 6180354!
See the manual page on integers for details.
回答2:
Remove the leading zero, because it makes PHP treat the number as an octal number.
回答3:
Because of the initial zero, it is interpreted as an octal number.
http://www.php.net/manual/en/language.types.integer.php
If the number should be left padded with zeros when printed (they are always a specific length) then you can use sprintf() to convert the stored integer to a zero padded string.
回答4:
Numeric literals with leading zeroes are how you specify something in octal (base 8). If you write 27447002
instead of 027447002
you'll be fine.
回答5:
Automatic base conversion. You don't even need all that class code to see this in action
echo 027447002;
The thing is that 027447002, in terms of numbers, is octal (base-8) - not a zero-filled decimal (base-10) integer.
回答6:
I have one comment besides what everyone else is saying.
It appears you want a 0 padded number, right? A nine digit number that's padded with zeros on the left?
Think about using str_pad function. Like so:
...
function bank($name, $id, $bal=0)
{
...
$this->id = str_pad($id, 9, '0', STR_PAD_LEFT);
...
}
...
Then in your function you can call:
$b = new bank('John Doe', 12345678, 1.25);
If you output id, it would be padded
012345678
回答7:
As everyone rightly said - this is considered an octal value by default. I think the class constructor should be testing that it is a valid integer, and initiating the class should typecast the value...
function bank($name, $id, $balance=0)
{
if (is_int($id))
$this->ID=$id;
else
throw new Exception('ID is not integer');
// and validate these too!
$this->balance=$balance;
$this->name=$name;
}
$b= new bank('yaniv', (int)027447002, 15000);
Hope that helps!
来源:https://stackoverflow.com/questions/1280039/strange-behaviour-on-php