php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #65553 Other typecasting magic methods
Submitted: 2013-08-25 19:51 UTC Modified: -
Votes:4
Avg. Score:3.0 ± 1.4
Reproduced:2 of 2 (100.0%)
Same Version:1 (50.0%)
Same OS:1 (50.0%)
From: wyattstorch42 at outlook dot com Assigned:
Status: Open Package: Class/Object related
PHP Version: Irrelevant OS: N/A
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: wyattstorch42 at outlook dot com
New email:
PHP Version: OS:

 

 [2013-08-25 19:51 UTC] wyattstorch42 at outlook dot com
Description:
------------
I am requesting other magic methods for automatic type conversion of objects, 
besides __toString(), in particular, __toArray(). The default method of converting 
an object to an array is, in my opinion, rather odd, since it provides the values 
of inaccessible properties and uses weird conventions, like an asterisk for 
protected properties and prefixing the class name for private properties.

Test script:
---------------
class Example {
   protected $a, $b, $c;

   public function __construct ($a) {
      $this->a = $a;
      $this->b = 'B';
      $this->c = 'C';
   }

   public function __toArray () {
      // Only return a and b, and don't distinguish scope
      return array (
         'a' => $this->a,
         'b' => $this->b
      );
   }
}

for ($examples = array (), $i = 0; $i < 3; $examples[] = (array) new Example(++$i));
echo json_encode($examples, JSON_PRETTY_PRINT);

Expected result:
----------------
[
   {
      "a": 1,
      "b": "B"
   },
   {
      "a": 2,
      "b": "B"
   },
   {
      "a": 3,
      "b": "B"
   }
]


Patches

Add a Patch

Pull Requests

Add a Pull Request

 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat May 11 00:01:31 2024 UTC