By Reference Parameters

Hi Experts,

Does PHP support passing parameters by reference, where you will have a function call like my_function($var1, $var2) and my_function will have the ability to change var1, var2, which will be seen by the calling code.  For example:

$var1 = 1;
$var2 = 2;

my_function($var1, $var2);
$var3 = $var1 + $var2 //would equal 5

my_function($var1, $var2){
$var1 = 2;
$var2 = 3;
}

Open in new window


if this possible in PHP, and more so in a class public static function? If not, how can I accomplish this?
APD TorontoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
Here's the page for 'functions': http://php.net/manual/en/functions.arguments.php  And I think this is the page you want for classes: http://php.net/manual/en/language.oop5.references.php

What you have to watch out for is exceptions.  Some functions require references and others require values.

http://php.net/ is always your friend in things like this.
0
Dave BaldwinFixer of ProblemsCommented:
After re-reading your code sample above, I would have to say I would never do that.  I seriously avoid re-using variable names because it is confusing when you have to troubleshoot the code.  And in my experience, you Always have to troubleshoot the code.  I would do something like this.
$var1 = 1;
$var2 = 2;

my_function($var1, $var2);
$var3 = $var1 + $var2 //would equal 5

my_function(&$var11, &$var22){
$var11 = 2;
$var22 = 3;
}

Open in new window

This does not prevent you from using references but it would tell me that the variables in the function aren't necessarily the ones outside.  Note the '&' for "pass by reference".
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Dave BaldwinFixer of ProblemsCommented:
Here's simple working demo of your code, both by value and by reference.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Passing methods</title>
</head>
<body>
<h1>Passing methods</h1>
<h2>By value</h2>
<?php 
$var1 = 1;
$var2 = 2;

my_function($var1, $var2);
$var3 = $var1 + $var2; //would equal 5

echo '$var3 = '.$var3.'<br>';

function my_function($var11, $var22) {
$var11 = 2;
$var22 = 3;
}

?>
<h2>By reference</h2>
<?php 
$var1a = 1;
$var2a = 2;

my_functiona($var1a, $var2a);
$var3a = $var1a + $var2a; //would equal 5

echo '$var3a = '.$var3a.'<br>';

function my_functiona(&$var11a, &$var22a){
$var11a = 2;
$var22a = 3;
}
?>
</body>
</html>

Open in new window

0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Mark BradyPrincipal Data EngineerCommented:
Dave makes a great and important point here. If you choose to go down the track of changing variables inside of functions it makes it difficult and in a large script, time consuming to debug. I have never done this in all my years as a programmer outside of a class, however inside a class I do quite often manipulate a variable that is used by the entire class. Consider something simple like this.

class Test {
    public function __construct() {
        $this->master_results = array(); // declare an empty array that is available anywhere in       this class.

    {

    public function get_user_details ($userid) {
        // get user details from database with a query then
        $this->master_results['username'] = 'John';
        // get his hobbies
        $this->get_hobbies($userid); // this adds the hobbies to the master_results variable
    }

    private function get_hobbies ($userid) {
        // do a query and get his hobbies assign it to $hobbies then
        $this->master_results['hobbies'] = $hobbies;
    }
}

$my_app = new Test();
$my_app->get_user_details('1234');
print_r ($my_app->master_results);

Open in new window


Now this is not very practical but it shows you how to manipulate one variable inside of any function inside this class by using the $this->variable_name.

No mtter if you are inside a class or just a regular php script you can do the same in two ways. Like Dave said, you can put an '&' in front of the variable name inside your function and manipulate the variable values like that, or you can declare them global inside your function like this.

$my_variable = 2;
// put it through your function

$my_variable = whatever() ;
echo $my_variable; // this would echo out 5

function whatever() {
    global $my_variable;
    $my_variable = 5;
}  

PHP has many ways of achieving things but good practices come into play so you would be good to read some tutorials and like Dave said, php.net is a great resource we all go to regularly (Yep even the experts refer to the good manual from time to time)
0
Dave BaldwinFixer of ProblemsCommented:
Yep even the experts refer to the good manual from time to time
No, ALL the time.  Why try to remember everything when I can just look it up?  And Ray's demo code always has links to the appropriate pages for the functions he is using in his demos.
0
Ray PaseurCommented:
This is a commonly asked question, and we have an article here that shows the difference between passing by copy and passing by reference.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12310-PHP-Variables-and-References.html

in a class public static function?
After you read the article, you can just try it if you want.  But I would not do that - instead return a value-object* and use an explicit assignment statement.  You code will be clearer (easier to read and understand the intent) and there is no penalty in performance.

* This is a term of art in object-oriented design.
0
Mark BradyPrincipal Data EngineerCommented:
No, ALL the time

Ok agreed - at least a few times a week :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.