Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Only variables can be passed by reference

I am getting this error on line 57: $password = str_replace($key, $value, $password, 1);

As far as I can tell, I am only passing in variables. Here is some more context:

$replace_count = 0;
foreach($replacables as $key => $value)
{
    if($replace_count >= 2)
        break;
    if(strpos($password, $key) !== false)
    {
        $password = str_replace($key, $value, $password, 1);
        $replace_count++;
    }

}
like image 293
Edward Yu Avatar asked Jun 24 '13 15:06

Edward Yu


People also ask

Are PHP variables passed by reference?

PHP variables are assigned by value, passed to functions by value and when containing/representing objects are passed by reference.

Is PHP pass by value or pass by reference?

Introduction. In PHP, arguments to a function can be passed by value or passed by reference. By default, values of actual arguments are passed by value to formal arguments which become local variables inside the function. Hence, modification to these variables doesn't change value of actual argument variable.

Are PHP arrays passed by reference?

With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified.

What is Call by reference in PHP?

In case of PHP call by reference, actual value is modified if it is modified inside the function. In such case, you need to use & (ampersand) symbol with formal arguments. The & represents reference of the variable. Let's understand the concept of call by reference by the help of examples.


2 Answers

Passing 1 there makes no sense. (Why not pass 42, or -5?) The 4th parameter of str_replace is only used to pass information back to you. The function does not use the original value of the variable at all. So what would be the point (even if allowed) of passing something in, if it is not used, and you are not going to use the new value sent back to you? That parameter is optional; just don't pass anything at all.

like image 35
newacct Avatar answered Oct 02 '22 21:10

newacct


You can't pass a constant of 1, a fix is to set it to a variable as so.

Change:

$password = str_replace($key, $value, $password, 1);

to:

$var = 1
$password = str_replace($key, $value, $password, $var);

UPDATE: Changed to declare variable outside of the method call from feedback in comments.

like image 52
immulatin Avatar answered Oct 02 '22 21:10

immulatin