简体   繁体   中英

PHP: Calling a function inside html of a variable

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.

<?php 
function example_function() {
// code
}

$form = '
<form action" <!-- etc. --> >
<input value="' . example_function() . '">
<input <!-- etc. --> >
</form>';
?>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM