Sign in to follow this  

[web] Out parameters in PHP functions?

This topic is 4202 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

// 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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4202 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this