|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-02-23 19:47 UTC] slusarz at curecanti dot org
Description: ------------ Per http://www.php.net/manual/en/language.types.array.php, array keys can be integers or strings. If an object can be converted to a string representation (i.e. it has a __toString() method defined), it should be automatically cast to a string. Currently, an error is thrown instead. Current workaround is to manually cast to string when setting a key. Test script: --------------- class Foo { public function __toString() { return 'A'; } } $a = new Foo(); $b = array($a => 1); print_r($b); Expected result: ---------------- Array ( 'A' => 1 ) Actual result: -------------- PHP Warning: Illegal offset type [...] Array ( ) PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 17:00:01 2025 UTC |
This feature is much awaited, it has wide practical application. For example in ORM system fields references could be objects: class FieldReference { protected $name; public function __construct($name) { $this->name = $name; } public function __toString() { return $this->name; } } $ref = new FieldReference('field'); echo $ref, "\n"; // outputs: field, __toString() method is called $select = [ // works fine but (string) clutters code (string) $ref => 'value' ]; var_dump($select); // outputs: array(1) { ["field"]=> string(5) "value" } $select = [ // looks fine but triggers: Warning: Illegal offset type (string) $ref => 'value' ]; var_dump($select);