Page 1 of 1

When a function's parameter contains a variable

Posted: Sun Jan 25, 2009 4:19 pm
by mikeLester
I need to pass a string to a function that contains code.

Part of the code is a variable. ($number)

The code needs to be evaluated in the function and return another string.

I would expect the following code to print out
"The number is 123. It is passed from the function. "
but it prints out
"The number is $number. It is passed from the function. "

I am sure I am doing something simplely wrong????

Code: Select all

 
<html>
<body>
<?php
 
$test = 'The number is $number.  It is passed from the function. ';
 
       
$tempStr =  showNumber($test);   // this is function shown below
echo($tempStr);
 
// ----------------------------- 
function showNumber($t)
{
  $number = 123;
  $outString = $t;
 
  return $outString;
}
 
?>
</body>
 

Re: When a function's parameter contains a variable

Posted: Sun Jan 25, 2009 4:40 pm
by Apollo
First, $variables inside single-quoted strings are not parsed. So you'd need double quotes. See the php manual on strings. Example:

Code: Select all

$x = 'green';
$a = 'I like $x apples'; 
$b = "I like $x apples";
echo $a . '<br>' . $b;
Will output:

I like $x apples
I like green apples


Second, when you do $test = "some string with $number inside", then the $number variable is evaluated at that moment. It's not like the strings keeps a magical reference to the $number variable, and when you change $number later on, the string would change along.

For what you want, some string replacement should do the trick. For example:

Code: Select all

$test = 'The number is [number]. It is passed from the function.';
 
$tempStr =  showNumber($test);   // this is function shown below
echo($tempStr);
 
// -----------------------------
function showNumber($t)
{
  $number = 123;
  $outString = str_replace('[number]',$number,$t);
  return $outString;
}
Note that [number] is just some unique identifier, you can use anything you want there to replace.

Re: When a function's parameter contains a variable

Posted: Sun Jan 25, 2009 4:58 pm
by John Cartwright
I find sprintf() much better than str_replace() for formatting strings since we can also cast the type of our input.