Cannot use object of type %s as array

Description

An object is not an array: as such, it cannot use the array syntax [1], based on square brackets, but the object syntax, with the object operators -> and ?->.

A class may be made compatible with the array syntax, by implementing the ArrayAccess. Then, it is possible to use the array syntax.

The scalar types are also forbidden to use the array syntax, although they are currently generating a warning, while the same error yields a Fatal Error.

Example

<?php

class X {}

$x = new X;
echo $x[0];

?>

Literal Examples

  • Cannot use object of type x as array

Solutions

  • Cast the object to array before using the array syntax.

  • Implement the ArrayAccess interface on the class.

  • Use the object operators on the object.

See Also