Is it possible to extend the PHP echo
so that I can run some extra processing code on every string being displayed? I need a way to sanitize all outputs and don't want to have to call strip_tags
on every display manually.

- 12,225
- 24
- 81
- 119
-
Why can't you write your own function, say `strip_echo`? – casablanca Mar 05 '11 at 15:53
-
There is a lot of code that uses echo in many, many parts of the code, and I don't want to have to go and manually change them. – chustar Mar 05 '11 at 15:57
-
Might be a duplicate of this: http://stackoverflow.com/questions/2182743/can-i-override-the-php-built-in-function-echo – Sergey Mar 05 '11 at 16:01
-
3echo is a language construct, it's not a function, so it can't be extended – Marc B Mar 05 '11 at 16:04
3 Answers
You cannot change the behaviour of echo
but you could make use php's output buffering functions (see the callbacks). However, this seems like overkill. As casablance suggested: create a function.

- 9,103
- 1
- 31
- 33
chustar,
write your own class with static methods and put it in app/libs.
Edit0: You are a programmer, write the code that changes the code.

- 2,185
- 1
- 14
- 19
@chutstar, If you're on Linux, you can use sed to find and replace all 'echo' with 'strip_echo' in the .php files in a directory, recursively.
Below is how Zend framework replaced all 'require_once' with '//require_once', EXCEPT for 'require_once' that appears in file Loader/Autoloader.php or Application.pp
#!/bin/sh # cd path/to/ZendFramework/library # replace all 'require_once' with '//require_once' , and skip Autoloader.php & Application.php find . -name '*.php' -not -wholename '*/Loader/Autoloader.php' -not -wholename '*/Application.php' -print0 | xargs -0 sed --regexp-extended --in-place 's/(require_once)/\/\/ \1/g'
So YOUR script should be
#!/bin/sh # replace all 'echo' with 'strip_echo' # cd path/to/ZendFramework/library find . -name '*.php' -print0 | xargs -0 sed --regexp-extended --in-place 's/echo/strip_echo/g'
I tested and it works. There might be unexpected replaces that you should check though, for example when 'echo' is accidentally part of some other function names or variables, etc..

- 783
- 2
- 7
- 10