Reputation: 123
I have a variable which stores the HTML code for a form, but I would like to add a PHP function inside. Here's what it looks like:
<?php
function example_function() {
// code
}
$form = '
<form action" <!-- etc. --> >
<input <!-- etc. --> >
<input value="<!-- example_function() should go here -->" <!-- etc. --> >
</form>';
?>
Any ideas on how I would add that function in there? I looked at many other similar topics, but none of them seemed to resolve this problem (I also had a look at Variable Functions in the documentation, but I don't think that would solve the problem).
Note: the form works fine without the function.
Upvotes: 0
Views: 701
Reputation: 7562
<?php
function example_function() {
// code
}
$form = '
<form action" <!-- etc. --> >
<input value="' . example_function() . '">
<input <!-- etc. --> >
</form>';
?>
Upvotes: 3
Reputation: 29856
This can be done using the eval function:
http://php.net/manual/en/function.eval.php
But be careful, from the manual:
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
If you do not want to store the function, but use the output of it, you can also concatenate the output of it with the other strings:
$form = '
<form action" <!-- etc. --> >
<input <!-- etc. --> >
'.example_function().'
<input <!-- etc. --> >
</form>';
You should do that if it satisfies your needs.
Upvotes: 0