0

Do you remember that previously when you would use a boolean as an array, php would send a notice, but with php8 that notice is a warning now?

$obj = false;
var_dump($obj); /* false */
var_dump($obj[1]); /* null (and warning now) */

Is there a way to create an object/class that has that same behaviour? In other words, can you create a class that when assigned directly to a variable behaves as one data type but that class can also be consumed as an array and return a different value/data-type?

  • You could write a class containing an array and have a get method return false if the array is empty. Does https://stackoverflow.com/questions/30924112/php-get-value-from-function-called-by-constructor help you? – Skip Dec 21 '22 at 19:01
  • I can't think of a use case for this. Having variables that suffer from this sort of polymorphia just smells bad to me. – Tangentially Perpendicular Dec 21 '22 at 19:02
  • 1
    Yes, but only if the type in _"behaves as one data type"_ is `object`. You could write a class that implements ArrayAccess. Assigning it directly would give you an object, referring to it as an array would give you whatever type you return from that method. – Alex Howansky Dec 21 '22 at 19:05
  • @TangentiallyPerpendicular indeed is a bad practice, I'm trying to mantain legacy code that has that behaviour, and management wants to keep all the code the same without launching warnings. – AlanVelasco Dec 21 '22 at 19:05
  • @AlexHowansky I'll look into ArrayAccess, didn't know the concept. Thanks – AlanVelasco Dec 21 '22 at 19:06
  • Making the object return NULL when accessed as an array is the _easy_ part. How do you all propose that you resolve `$obj == false`? What is there's a `$obj === false` lurking in the code somewhere? I would suggest not wasting your time on this and fixing the bugs in the legacy code instead. – Sammitch Dec 21 '22 at 19:16

0 Answers0