php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #81629 Error casting object to array
Submitted: 2021-11-17 08:37 UTC Modified: 2021-11-17 14:16 UTC
From: newed2008 at gmail dot com Assigned: nikic (profile)
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.4.25 OS:
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: newed2008 at gmail dot com
New email:
PHP Version: OS:

 

 [2021-11-17 08:37 UTC] 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)
}

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-11-17 13:35 UTC] cmb@php.net
-Package: *General Issues +Package: Scripting Engine problem -Assigned To: +Assigned To: nikic
 [2021-11-17 13:35 UTC] 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 13:38 UTC] nikic@php.net
-Status: Assigned +Status: Not a bug
 [2021-11-17 13:38 UTC] 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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Dec 30 14:01:28 2024 UTC