Req #64320 [Opn->Fbk]: Proposal: deprecate the "leading 0 means octal" behaviour
Edit report at https://bugs.php.net/bug.php?id=64320&edit=1
ID: 64320
Updated by: nikic@php.net
Reported by: php at richardneill dot org
Summary: Proposal: deprecate the "leading 0 means octal"
behaviour
-Status: Open
+Status: Feedback
Type: Feature/Change Request
Package: Math related
Operating System: All
PHP Version: 5.4.12
Block user comment: N
Private report: N
New Comment:
Could you maybe provide a testcase for the behavior you are referring to? I tried out the following
and "010" wasn't interpreted as octal in any case:
var_dump((int) "010", intval("010"), "010" == 8);
// Outputs: int(10) int(10) bool(false)
010 is only treated as an octal if you write it out plainly (in the source code), like $foo = 010;
Previous Comments:
------------------------------------------------------------------------
[2013-02-28 13:41:48] php at richardneill dot org
Description:
------------
PHP assumes that a string with a leading zero should be interpreted as octal.
In my experience, this is almost never useful, desirable, or intentional, however, it is a frequent
trap for the beginner (or more experienced programmer), especially when parsing user-submitted data.
The only reason for this behaviour seems to be historical, and compatibility with strtol(). When
non-programmer humans write numbers with leading zeros, they don't usually mean base 8.
My proposal is:
1. Introduce a new string format, 0o#### (letter o), to explicitly mean "this is an octal
number". This is similar to the recent introduction of 0b#### for binary numbers.
[This part should be simple to do, and would also make the intentional use of octal notation
explicit, increasing code-readability]
2. Add an option to raise E_NOTICE any time a number is implicitly interpreted as octal (for example
"$x = 0100").
3. In a few years time, (PHP 7?), it may finally be possible to change the default behaviour.
Test script:
---------------
Here's an illustration of a naive program that has data-dependent bugs that are really hard to
track down.
$mass_kg = "0.314" //user-submitted data, known to begin "0."
$mass_g = substr ($mass_kg, 2);
Yes, this is a silly thing to write. But it's a nasty trap for the unwary.
The above example does what is expected, and might pass many tests. But if the user subsequently
enters $mass_kg = "0.031", this will turn into 25 grams, not 31 grams. As a result, we
have created a very subtle and hard to find bug.
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=64320&edit=1
Thread (3 messages)