No Force Object To String
<?php
class A {
function __toString() {
return 'A';
}
}
$a = new A();
$b = [$a => $a];
print_r($b);
PHP automatically converts numeric strings to integers when used as array indices, so ‘123’ becomes 123 (the integer). However, PHP doesn’t perform similar conversions for objects, when they are used as array keys. Instead, it immediately throws a fatal Illegal offset type error because objects are not automatically converted to valid array keys.
See Also
- Arrays (PHP manual)
- Cast to object as key [Try me]
PHP Error Messages
PHP Features
Last updated: 09 November 2026