php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #74150 Passing null value and default restriction
Submitted: 2017-02-22 16:12 UTC Modified: 2017-02-22 17:23 UTC
From: aaatoja at o2 dot pl Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 7.1.2 OS: Debian
Private report: No CVE-ID: None
 [2017-02-22 16:12 UTC] aaatoja at o2 dot pl
Description:
------------
Shouldn't code below throw TypeError exception: Argument 1 passed to test::a() must be of the type string, null given? Nullable type is not allowed here. This should work only with a(?string $x=null)

Test script:
---------------
class test {
    public function a(string $x=null) {
        echo 'a';
    }
}

$x = new test;
$x->a(null);

Expected result:
----------------
TypeError exception

Actual result:
--------------
Null value as an argument is accepted.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-02-22 16:53 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2017-02-22 16:53 UTC] requinix@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
> The declaration can be made to accept NULL values if the default value of the
> parameter is set to NULL.
 [2017-02-22 17:04 UTC] aaatoja at o2 dot pl
Ok, but starting with 7.1 it doesn't make sense:

"Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated"

a(string $test=null) // incorrect type, should throw error
a(string $test='test') // valid type, ok
a(?string $test=null) // valid type, ok
a(?string $test='test') // valid type, ok
 [2017-02-22 17:23 UTC] requinix@php.net
Had nullable types been ready for 7.0 then maybe "string $x=null" would not have been allowed. But it was not, and since scalar type declarations was, there needed to be some way to use the declarations but still permit null as a default (as it is a standard convention). =null was how that happened.

"string $x=null" will not be confined to only the 7.0 series. That would create chaos. It may be deprecated and removed at some point in the future, but that is not on the radar. If you want to spur on that discussion then learn about the RFC process.
https://wiki.php.net/rfc/howto
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 04:01:28 2024 UTC