andrefrua
andrefrua

Reputation: 33

PHP By Reference variable

I'm a .net programmer that recently decided to check PHP out and so far I must say that it's quite fun.

I use WAMPServer to work with PHP and I'm having a problem when using by reference variables.

This is the code I'm using:

function drawCategories($parent_id, $catlistids="",$level=0,$selected="") {
    global $USERLANG;
$result = mysql_query("
    SELECT 
        BPPENNYAUTOBID_categories.cat_id,
        BPPENNYAUTOBID_cats_translated.cat_name 
    FROM
        BPPENNYAUTOBID_categories 
            INNER JOIN BPPENNYAUTOBID_cats_translated ON BPPENNYAUTOBID_categories.cat_id=BPPENNYAUTOBID_cats_translated.cat_id
    WHERE
        BPPENNYAUTOBID_cats_translated.cat_name!='' 
        AND BPPENNYAUTOBID_categories.parent_id='".$parent_id."' 
        AND BPPENNYAUTOBID_cats_translated.lang='".$USERLANG."' 
    ORDER BY 
        BPPENNYAUTOBID_categories.cat_name"
);

    while ($line = mysql_fetch_array($result)) {
        if($catlistids != "") { $catlistids .= "<br />"; }
        $spaces = "";
        for($i=0;$i<$level;$i++) $spaces .="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        $catlistids .= "<option value='".$line['cat_id']."' ".($selected==$line['cat_id'] ? " selected ":"").">".$spaces.$line["cat_name"]."</option>";


        drawCategories($line["cat_id"], &$catlistids,$level+1,$selected);
 }
 return $catlistids;
}

When I call the drawCategories function the second time passing the variable $catlistids by reference then all the website content disapears, I don't get any kind of error but I suppose it's something to do with WAMP server definitions.

Can anyone help me solve this problem?

Thanks in advance

Upvotes: 1

Views: 127

Answers (1)

Vahid Hallaji
Vahid Hallaji

Reputation: 7447

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

You can pass a variable by reference to a function so the function can modify the variable. Remove & from function call and try this way:

function drawCategories($parent_id, &$catlistids="", $level=0, $selected="") {
                                  //^

Upvotes: 1

Related Questions