I know in php you can embed variables inside variables, like:
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
But I was wondering how, and if it was possible to include a function inside a variable. I know I could just write:
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions:
<?php
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
There is <b>alot</b> of text and html here... but I want some <i>functions</i>!
-somefunc() doesn't work
-{somefunc()} doesn't work
-$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string
-more non-working: ${somefunc()}
</body>
</html>
EOF;
?>
Or I want dynamic changes in that load of code:
<?
function somefunc($stuff) {
$output = "my bold text <b>{$stuff}</b>.";
return $output;
}
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
somefunc("is awesome!")
somefunc("is actually not so awesome..")
because somefunc("won\'t work due to my problem.")
</body>
</html>
EOF;
?>
Well?
we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; }; if we simply call this function, nothing will be printed, although nothing is wrong with the writing of the function itself.
It is possible to define a function from inside another function. the inner function does not exist until the outer function gets executed.
You need to instantiate (create) $newVar outside of the function first. Then it will be view-able by your other function. You see, scope determines what objects can be seen other objects. If you create a variable within a function, it will only be usable from within that function.
After declaring a variable or function with the var keyword, you can call it at any time by invoking its name.
Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call:
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
will output "foo <b>bar</b> baz
".
I find it easier however (and this works in PHP4) to either just call the function outside of the string:
<?
echo "foo " . somefunc("bar") . " baz";
?>
or assign to a temporary variable:
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
"bla bla bla".function("blub")." and on it goes"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With