Skip to content

PHP8.2 Disjunctive Normal Form Types with a default value of null #9655

Closed
@HypeMC

Description

@HypeMC

Description

There seems to be some inconsistent behavior with Disjunctive Normal Form Types when an argument has a default value of null.

Usually if the default value is null, the argument is implicitly nullable, eg:

<?php
function foo(string $param = null) { var_dump($param); }
function bar(\Foo\Bar|\Foo\Baz $param = null) { var_dump($param); }

foo(null);
bar(null);

result:

NULL
NULL

https://3v4l.org/iBlne

An exception to this rule are PHP 8.1 intersection types:

function foo(\Foo\Bar&\Foo\Baz $param = null) { var_dump($param); }

foo(null);

result:

Fatal error: Cannot use null as default value for parameter $param of type Foo\Bar&Foo\Baz in /in/k0OjD on line 3

Process exited with code 255.

https://3v4l.org/k0OjD

However, the same error is raised on PHP 8.2, even though the following works:

function foo((\Foo\Bar&\Foo\Baz)|\Foo\Qux $param = null) { var_dump($param); }

foo(null);

result:

NULL

https://3v4l.org/UADDP

With the introduction of DNF types, I would expect \Foo\Bar&\Foo\Baz $param = null to implicitly mean (\Foo\Bar&\Foo\Baz)|null $param = null, which works as expected:

function foo((\Foo\Bar&\Foo\Baz)|null $param = null) { var_dump($param); }

foo(null);

result:

NULL

https://3v4l.org/gjOAp

PHP Version

PHP 8.2rc3

Operating System

Ubuntu 22.04

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions