Bug #79377 [Nab]: Property is not cloned with clone
| From: | requinix@php.net | Date: | Fri, 13 Mar 2020 01:38:35 +0000 |
| Subject: | Bug #79377 [Nab]: Property is not cloned with clone | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-226084@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=79377&edit=1
ID: 79377
Updated by: requinix@php.net
Reported by: mvorisek at mvorisek dot cz
Summary: Property is not cloned with clone
Status: Not a bug
Type: Bug
Package: Scripting Engine problem
Operating System: Any
PHP Version: 7.4.3
Block user comment: N
Private report: N
New Comment:
Regarding the code from your email, https://3v4l.org/Q557K
References are not pointers.
> $test = &$x->elements;
$test will not "point" to $x->elements. It will not be a reference "to" that
property. Rather, this reference assignment will make it so that both of those symbols use the same
data that is being stored internally by the engine. They are *both* references. Then when PHP clones
the object, the property will be copied - including the fact that it is a reference (thus resulting
in a *third* reference).
See https://www.php.net/manual/en/language.references.php
As a rule of thumb, whatever the problem may be, using references is *not* the solution.
Previous Comments:
------------------------------------------------------------------------
[2020-03-13 00:59:13] requinix@php.net
You made the property a reference. PHP quite happily cloned the reference.
------------------------------------------------------------------------
[2020-03-13 00:57:32] mvorisek at mvorisek dot cz
Description:
------------
Seems like a core bug presented in all PHP versions (5.4.0 - 7.4.3 tested).
Please verify and fix asap.
Test script:
---------------
class A {
public $elements = [];
public function __construct()
{
$this->fields = &$this->elements; // this causes the issue
}
public function __clone()
{
// $elems = $this->elements; unset($this->elements); $this->elements = $elems;
$this->fields = &$this->elements; // this is an immediate fix before fixed in PHP directly
}
}
$x = new A();
$y = clone $x;
$y->elements['hello'] = 'world';
print_r($x);
print_r($y);
Expected result:
----------------
A Object
(
[elements] => Array
(
)
[fields] => Array
(
)
)
A Object
(
[elements] => Array
(
[hello] => world
)
[fields] => Array
(
[hello] => world
)
)
Actual result:
--------------
A Object
(
[elements] => Array
(
[hello] => world
)
[fields] => Array
(
[hello] => world
)
)
A Object
(
[elements] => Array
(
[hello] => world
)
[fields] => Array
(
[hello] => world
)
)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=79377&edit=1