Skip to content
Advertisement

How to call a function in a string using PHP

I wrote a function to dynamically insert the default date in a drop down option tag. In my function called pickDate I echo out the string at the end with double quotes. Then later in my code I have a for loop that produces a new string and inside the string I am trying to call my function.

My problem is that when I call pickDate() in my string it is rendering out pickdate() (literally) and not the result of the function. Looking at my code, my question is : how do I call a function within a string surrounded by double quotes.

I want to know how I can call it in the string in this for loop below:

<?php
$displayFolder .= "<form action='gallery.php' enctype='multipart/form-data' method='post' name='editPic' 

id='editPic'><tr><td>
pickDate()
<input type ='text' name='year' size='4'maxlength='4' 

value='$year'/></form></td> </tr>";
?>

So the problem again is calling the pickDate function cause it is in a string and I would like to know how I can out put the pickDate() result in the table. I like how it is all surrounded by double quotes. Can someone please tell me how to call the function properly in the string without having to change my string to much.

Advertisement

Answer

Replace this:

$displayFolder .="<form action='gallery.php' enctype='multipart/form-data' method='post' name='editPic' 

id='editPic'><tr><td>
pickDate()
<input type ='text' name='year' size='4'maxlength='4' 

value='$year'/></form></td> </tr>";

With this:

$displayFolder .="<form action='gallery.php' enctype='multipart/form-data' method='post' name='editPic' 

id='editPic'><tr><td>
".pickDate()."
<input type ='text' name='year' size='4'maxlength='4' 

value='$year'/></form></td> </tr>";

The only change needed above was isolating your pickDate() function from the rest of the string using the concatenation operator (the dot). Also, in order for this to work, your pickDate() function must return its result instead of outputting directly, otherwise it’ll output its contents as soon as $displayFolder is defined. To fix that, replace this:

echo "$monthOption";

With this:

return $monthOption;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement