2

Is there a way to extend the native PHP array with a __toString() function/method?

I would like to be able to do

$a = array($x, $y, $z);
echo $a;

This should neither complain with a Array to string conversion notice nor the dull output of Array but instead do whatever I implement in the __toString() method of the array.

(In the __toString I would do something like iterate over the array and call __toString() on each element and concatenate that together to a string that describes the whole array.)

(I know that this can be done through e.g. a wrapper object, that's not the question. I want to tweak PHP on a more subtle level.)

raoulsson
  • 14,978
  • 11
  • 44
  • 68
  • Not natively without an extension - you can use ArrayObject – Mike B Jan 30 '14 at 14:19
  • 1
    Use `echo implode('',$a);` ? – Aditya Jan 30 '14 at 14:20
  • Using `implode()` might result in something unrecoverable if the data contains csv metadata - `serialize()` is safer. However to use an arbitrary encoding scheme, `array_reduce()` might be the right approach. – symcbean Sep 01 '18 at 15:04

1 Answers1

1

Php arrays are not objects, it's an ordered map. The most relevant documentation is maybe the one concerning Arrays

As mike said, the only way to add a method for array manipulation is using ArrayObject which is closer to array than what you can find in other languages.

But:

ArrayObject implies the use of Iterator, but it's OO.

wako
  • 24
  • 4