Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

PHP Error Messages

PHP Features

Last updated: 09 November 2026