[web] Out parameters in PHP functions?

Started by
4 comments, last by konForce 17 years, 10 months ago
I've googled around a bit, but can't find any information on out parameters from PHP functions. I know that this functionality exists, at least in the built-in functions, because the ereg and preg functions have output parameters. The language documentation on functions doesn't mention how to do this, though. How do you do out parameters in PHP?
Advertisement
Put an ampersand before the parameter name when declaring the function:
function myfunc($in, &$out){   $out = $in + 1;}
What you can't have in user-defined functions in PHP, is optional reference parameters.

But some of the library functions (you mentioned preg_match) *do* have them. This is an example of an inconsistency in PHP (just one of many :) )

Mark
// PHP4 (I'm pretty sure this works...)<?php        function foo($a, &$b)        {                print $a."\n";        }        @foo("bar");?>// PHP5<?php        function foo($a, &$b = NULL)        {                print $a."\n";        }        foo("bar");?>


The output is:
bar


There you have a user defined, optional reference parameter. And it is clearly stated in the manual: php.net/functions_arguments.
Bear in mind that I'm defining "works" as "works without generating any notices, errors or warnings of any kind during normal operation".

I always have an error handler which will take drastic action in any such case; I can't bear calling normal functions generating even a notice.

Mark
Of course the method I illustrated for version 4 is a kludge, but it does show that you can "have" optional references. But it's not fair to say PHP doesn't support something when you aren't using the latest major production version. It's been out for almost two years now, which is plenty enough time to convert the few lines of incompatible code from legacy applications. And if your shared hosting provider doesn't support it, find one that does. There are a million and one hosting companies out there.

But really, passing parameters by reference is not particularly good anyway. While it can be very useful, it can be cryptic at times. In many cases, a proper user defined class that maintains it's own internal variables is a better solution.

This topic is closed to new replies.

Advertisement