Is there some way to "hook into" PHP's "echo" mechanism?

Viewed 98

For a long time now, I have had my own wrapper function around echo, so that instead of:

echo 'This is an example.';

I do (in CLI scripts):

terminal_output('This is an example.');

This allows me to, for example, do fancy outputting of the text on the terminal. For example, I can make it look like it's "typed out" with random delays.

Sometimes, I realize that I have been using "echo" instead of my wrapper function, and then I have to sit and change them all into my function calls.

It strikes me that, maybe, there is some way to "hook into" the echo function so that I can indeed use echo everywhere, yet do any kind of fancy processing I feel like? And of course, that wrapper function would check whether it's in web or cli mode, and always directly output if in web mode.

I've oftentimes found hidden "gems" like this in PHP which are barely documented or well hidden, so maybe it's the case this time as well?

1 Answers

Functions can be namespaced. PHP native functions can be redefined with the same name in custom namespaces.

But echo is a special case. It is not a function, but is a language construct.

// echo supports non-function-shape calls since it's a language construct.
echo "string", "string";

AKAIK, the language may not allow you to define a function with that name.

Related