6

Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical?

I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses arrays everywhere if I substituted them with a custom Array class.

Wilco
  • 32,754
  • 49
  • 128
  • 160

3 Answers3

7

The only problems i can think of are the gettype() and the is_array() functions. Check your code for

gettype($FakeArray) == 'array' 
is_array($FakeArray)

Because although you can use the object just like an array, it will still be identified as an object.

Bob Fanger
  • 28,949
  • 7
  • 62
  • 78
  • 2
    Even then, it looks like I could use the override_function() function to override those functions to account for additional cases. – Wilco Sep 28 '08 at 08:51
4

In addition to the points made above, you would not be able to make user-space array type hints work with instances of your class. For example:

<?php
function f(array $a) { /*...*/ }

$ao = new ArrayObject();
f($ao); //error
?>

Output:

Catchable fatal error: Argument 1 passed to f() must be an array, object given 
rewbs
  • 1,958
  • 4
  • 22
  • 34
3

Other differences include the '+' operator for arrays (merging) and the failure of the entire array_* functions, including the commonly used array_merge and array_shift.

A J
  • 3,970
  • 14
  • 38
  • 53
Eran Galperin
  • 86,251
  • 24
  • 115
  • 132