Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: "... variables can be passed by reference" in str_replace()?

Tags:

I created a function to print a prepared-statement-sql-string with the variables in it, based on what I found in this other StackOverflow question.

Here is my code:

foreach($params as $idx => $param) {     if ($idx == 0) continue;     $sql = str_replace('?', "'" . $param . "'", $sql, 1); } printError($sql); 

When I run this I get: Fatal error: Only variables can be passed by reference for line 3. However when i use

$sql = preg_replace('/\?/', "'" . $param . "'", $sql, 1);

for line 3 it works fine.

Any idea why?

like image 567
Dexter Avatar asked Apr 30 '11 14:04

Dexter


People also ask

Are PHP variables passed by reference?

TL;DR: PHP supports both pass by value and pass by reference. References are declared using an ampersand ( & ); this is very similar to how C++ does it. When the formal parameter of a function is not declared with an ampersand (i.e., it's not a reference), everything is passed by value, including objects.

What is meant by passing the variable by value and reference in PHP?

When the variable is passed as a reference then it is called pass variable by reference. Here, both the main variable and the passed variable share the same memory location and & is used for reference. So, if one variable changes then the other will also change.


2 Answers

The very last parameter, count, is passed by reference. You can see this in the description at http://us.php.net/str_replace where there's a & in front of the variable.

This means you cannot use a literal 1 there. You'd have to do:

$sql = str_replace('?', "'" . $param . "'", $sql, $count); echo $count; 

You'll now have displayed on the screen how many instances were replaced.

like image 91
VoteyDisciple Avatar answered Sep 28 '22 03:09

VoteyDisciple


Look at the documentation for preg_replace and str_replace and you will see why. str_replace's fourth argument must be passed by reference, but this is not the case for preg_replace.

like image 26
Explosion Pills Avatar answered Sep 28 '22 03:09

Explosion Pills