Jump to content

noob question about references


ballhogjoni

Recommended Posts

#1) In PHP Objects are always passed by reference.

 

For other stuff like strings, arrays, etc, you put the & in front of the variable in the argument list:

function myFunc(&$value){
  $value = 'This is changing the value both here and in the scrip';
}

 

Passing by reference just means you are passing the 'pointer' or 'reference' to the variable instead of the value. Normally, if you pass a variable (not applicable to objects as they are always by reference), it only passes the value. Then, assigns that value to the proper variable in the function. That variable is local to that function and exists only for the lifetime of that function call.

so basically if I were to pass an array that looks like this:

 

$value = array("1","2","3");

 

and pass it in as a reference, then in my function do this:

 

function myFunc(&$value){
  $value = 'This is changing the value both here and in the scrip';
  return $value;
}

 

it would output 'This is changing the value both here and in the scrip' in my script?

No, you wouldn't have to return it at all.  Try this code and see if you get it:

 

<?php

function noref($var) {
    $var = "Inside of function";
}

function yesref(&$var) {
    $var = "Inside of function";
}

$a = "Outside of function";
noref($a);
echo "$a\n";

$b = "Outside of function";
yesref($b);
echo "$b\n";

//Just to show you pass by reference without & in function header:
noref(&$a);
echo "$a\n";
?>

It may seem cool at first, but you really don't want to always be using references.  Sometimes its hard to track where variables are being edited if you do.  It would be better to do like:

 

<?php
function noref($var) {
    $var = "Inside the function.";
    return $var;
}

$a = "Outside the function";
$a = noref($a);
echo $a;
?>

 

Then you can clearly see where it's being modified.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.