|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2021-07-28 20:35 UTC] raincomplain at outlook dot com
Description:
------------
According to the RFC of "New in initializers":
Parameter default values are evaluated from left to right on every call to the function where the parameter is not explicitly passed.
So calling a method by not explicitly passing a default paramater and using named arguments to call other arguments should trigger default parameter evaluation, so far so good. However, if both arguments are objects of the same class that modify a static property, PHP only returns the copy of the default object and "overlooks" the other object that was passed as a named argument.
Test script:
---------------
class A
{
public static int $x = 0;
public function __construct(int $x)
{
self::$x = $x; // changing this to self::$x += $x; works as expected
}
}
function getTest(A $o1 = new A(88), A $o2 = new A(77))
{
return A::$x;
}
var_dump(getTest(o2: new A(55)))
Expected result:
----------------
int(55)
Actual result:
--------------
int(88)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Dec 22 23:00:01 2025 UTC |
This example is extremely weird. Let's make it more obvious by dropping the static property and just dumping in the constructor: <?php class A { public function __construct(int $x) { var_dump($x); } } function getTest(A $o1 = new A(88), A $o2 = new A(77)) { } getTest(o2: new A(55)); This prints int(55) followed by int(88), exactly as it should. First the new A(55) object is created explicitly and passed to parameter $o2, and then new A(88) is created when filling in the default value for parameter $o1.