简体   繁体   中英

strange behaviour on php

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?

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.

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.

删除前导零,因为它使PHP将数字视为八进制数字。

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.

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.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM