0

I have to convert an object into an array, but I want to omit some of the objects' properties.

class X {
   protected $a = 1;
   protected $b = 5;

   /**
    * Property 'a' should not exist in the resulting array
    */
   public function __toArrayOrSomething()
   {
       return [
           'b' => $this->b
       ];
   }
}

When I cast an object of this class into an array, the resulting array should e. g. look like this:

$x = new X();
$result = (array) $x;

$result should look like this:

[
    'b' => 5
]

I know there are dozens of ways to do a manual array conversion, but I need a solution for use with type-casting ($y = (array) $x;).

So the question is: Is there something like JsonSerializable::jsonSerialize for array-casting?

Or in other words: Is there a method that is called, when an object is casted into an array?

René Pöpperl
  • 567
  • 5
  • 18
  • Maybe it's better to implement `ArrayAccess`? – u_mulder Apr 02 '19 at 09:26
  • 1
    PHP has that kind of logic for string conversion, you can implement the magic method `__toString` for that, but there is no direct equivalent __toArray. – 04FS Apr 02 '19 at 09:30

0 Answers0