Passing variables by reference

Hi,

Just a double-check - I want to make a string clean-up function, you pass it some strings and they get modified, this is how it should look right?

Thanks



<?php
 
    function wow(&$string1, &$string2)
    {
        $string1 = "super";
        $string2 = "fantastic";
    }
 
    $test1 = "hello";
    $test2 = "world";
 
    wow($test1, $test2);
 
    // now test1 is "hello", test2 is "world".
?>

Open in new window

DJ_AM_JuiceboxAsked:
Who is Participating?
 
RobinSoftware EngineerCommented:
This is a way it will work.
For more info on passing parameter on reference, see http://www.php.net/manual/en/language.references.pass.php
0
 
Michael701Commented:
no,

// now test1 is "super", test2 is "fantastic".
   function wow(&$string1, &$string2)
    {
        $string1 = "super";
        $string2 = "fantastic";
    }
 
    $test1 = "hello";
    $test2 = "world";
    // now test1 is "hello", test2 is "world".
 
echo "test1: ".$test1." test2: ".$test2 ."<br />\n";
 
    wow($test1, $test2);
 
// now test1 is "super", test2 is "fantastic".
echo "test1: ".$test1." test2: ".$test2 ."<br />\n";

Open in new window

0
 
RobinSoftware EngineerCommented:
I guess his comments in the code were just a typo..  (?)
0
 
DJ_AM_JuiceboxAuthor Commented:
Ughh yeah sorry wasn't paying attention, thanks.
0
 
Ray PaseurCommented:
Here is a real-word example that avoids the confusion that can arise from the use of the & references.  It is always a better programming practice to have separate names for "unclean" and "clean" variables.  For example, if your code NEVER touches $_POST, except in the one place that purifies the incoming data in $_POST, you know you are never running a program with potentially dangerous data fields.

Code snippet teaches how to eliminate all but positive integers.

Best, ~Ray
// FORCE IT ALL NUMERIC
function clean_integer_string($string) 
{
   $new = trim(ereg_replace("[^0-9]", "", $string));
   return $new;
}
 
// USAGE
$string = abc123;
$clean  = clean_integer_string($string);
echo $clean; // PRINTS 123

Open in new window

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

All Courses

From novice to tech pro — start learning today.