Bug #81629 [Nab]: Error casting object to array
| From: | cmb@php.net | Date: | Wed, 17 Nov 2021 14:16:19 +0000 |
| Subject: | Bug #81629 [Nab]: Error casting object to array | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-237814@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=81629&edit=1
ID: 81629
Updated by: cmb@php.net
Reported by: newed2008 at gmail dot com
Summary: Error casting object to array
Status: Not a bug
Type: Bug
Package: Scripting Engine problem
PHP Version: 7.4.25
Assigned To: nikic
Block user comment: N
Private report: N
New Comment:
Added a brief note: <https://github.com/php/doc-en/commit/d332b5ae70bd27873fa1b51b366a721957042e69>.
Previous Comments:
------------------------------------------------------------------------
[2021-11-17 13:38:45] nikic@php.net
Yes, this is by design. Despite the innocuous syntax, (array) $object is a low-level reflection-like
operation (roughly) corresponding to get_mangled_object_vars($object). Things would break big-time
if it would throw for uninitialized properties.
------------------------------------------------------------------------
[2021-11-17 13:35:31] cmb@php.net
This might actually be by design. After all, casting object to
array doesn't follow the usual access rules (e.g. private
properties are contained in the array as well). If so, this would
be a documentation issue.
Nikita, could you please clarify?
------------------------------------------------------------------------
[2021-11-17 08:37:34] newed2008 at gmail dot com
Description:
------------
Following the strong typing in the class description, I expect that when casting an object to an
array, the array will match the described types or throw an exception.
In this example, I also have a property ($typeString) that cannot be null. I skipped the
initialization of this property in the code and expected that when I tried to transform such an
object to an array, I would get an exception like Typed property ... must not be accessed before
initialization, as if I access an uninitialized property.
I think if the property is in a typed class, then casting to an array should take into account
typing.
Test script:
---------------
class A
{
public int $typeNumber;
public string $typeString;
}
$a = new A();
$a->typeNumber = 1;
var_dump(
(array)$a
);
Expected result:
----------------
Uncaught Error: Typed property A::$typeString must not be accessed before initialization
Actual result:
--------------
array(1) {
["typeNumber"]=>
int(1)
}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=81629&edit=1