php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #49233 Type hinted parameter default value cannot be a class constant defined as null
Submitted: 2009-08-12 10:53 UTC Modified: 2015-03-14 16:03 UTC
Votes:7
Avg. Score:3.7 ± 1.3
Reproduced:6 of 7 (85.7%)
Same Version:1 (16.7%)
Same OS:2 (33.3%)
From: bar105 at zepler dot net Assigned: nikic (profile)
Status: Closed Package: Class/Object related
PHP Version: 5.2.10 OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: bar105 at zepler dot net
New email:
PHP Version: OS:

 

 [2009-08-12 10:53 UTC] bar105 at zepler dot net
Description:
------------
The parser does not permit the use of a class constant with the value NULL as a default value for a type-hinted function parameter.

Using class constants instead of specific values such as "NULL" promotes a cleaner API, and more easily readable code. 


consider the following function, which might retrieve data from a database either for a specific date or for all dates:
$foo->getInfo(Date::today());

// If given null, retrieve for all dates
$foo->getInfo(null);

// Using a class constant is much more readable
$foo->getInfo(Foo::ALL_DATES);


The parser should, imho, resolve the value of class constants before throwing an error stating the default value is not NULL and therefore not permitted.

Please consider correcting this behaviour.

Reproduce code:
---------------
class Foo {
    const NO_VALUE = null;

    public static function bar(Foo $param = self::NO_VALUE) {
        if ($param == self::NO_VALUE)
            echo "Param was NO_VALUE"
        else
            echo "Param was a valid instance of Foo";
    }
}

Expected result:
----------------
$myFoo = new Foo();

Foo::bar(my$Foo);
// "Param was a valid instance of Foo"

Foo::bar();
// "Param was NO_VALUE"

Actual result:
--------------
Fatal error: Default value for parameters with a class type hint can only be NULL

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-08-12 10:59 UTC] bar105 at zepler dot net
In the expected result, "my$Foo" should read "$myFoo".
 [2011-01-01 16:05 UTC] jani@php.net
-Package: Feature/Change Request +Package: Class/Object related
 [2015-03-14 16:03 UTC] nikic@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: nikic
 [2015-03-14 16:03 UTC] nikic@php.net
This has been fixed in PHP 5.6.4.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 20:01:45 2024 UTC