When a function's parameter contains a variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mikeLester
Forum Newbie
Posts: 2
Joined: Thu Jun 05, 2008 6:07 pm

When a function's parameter contains a variable

Post 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>
 
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: When a function's parameter contains a variable

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: When a function's parameter contains a variable

Post by John Cartwright »

I find sprintf() much better than str_replace() for formatting strings since we can also cast the type of our input.
Post Reply