For string functions, I find myself doing this kind of thing a lot:
$string = trim($string);
I would like to easily have functions where I can pass the string by reference, so I can instead do function($string);.
I was thinking about writing wrappers for all the string functions I want to use, and prefix it with a special character, like so:
function _trim(&$string) {
trim($string);
}
function _str_replace($a, $b, &$string) {
str_replace($a, $b, $string);
}
But I wonder if there’s a way that’s easier than writing a wrapper for each function? (Has someone written this library already?)
For functions that can take only one argument (the string) like
trim(),strtolower()etc, you could do something like this maybe…?…but to be perfectly honest, I cant really see the point – for one thing, you can’t chain functions that take an argument by reference (i.e. you can’t do
trim(strtolower($str)))I tend not to write
$str = trim($str);very much, because I am probably going to use the result fairly immediately in some other operation. Instead of this:I just do this:
And in the event that I need to do something like this:
I would do this:
…but whatever you are trying to do by doing any of the above, what you are effectively achieving is making your code less readable, and probably nothing else.
EDIT
After doing something completely unrelated today, I realised there is a way to chain functions and call it by reference:
…but I still maintain this is not the way to go.
ANOTHER EDIT
You could pass to functions that uses multiple arguments by doing something like this (untested):