Is it possible to use php functions inside heredoc? - php

Is it possible to use functions within the heredoc template without breaking it?
Somethig like this:
<<<HTML
<div> showcaptcha(); </div>
HTML;
Specifically i wanna require another template in this one without using variables.
Or is there another and more simple solution that is not using heredoc?
Thx in advanced.
For example im using class named requires.
class requires {
public function __construct(){
$this->MYSQL();
$this->FUNC();
}
public function MAIN_MENU() {
require_once ('main-menu.tpl');
}
}
Then what i do in index.php
require_once ('requires.php');
$req = new requires();
echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
//bla bla
</head>
<nav><ul class="fancynav">
{$req->HEAD_SCRIPTS()}
</ul></nav>
HTML;
main-menu.tpl
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
And in result i have an empty field without php error
<nav><ul class="fancynav">
</ul></nav>
WTF?

Yes, you can use the "encapsed var" trick:
function hello() {
global $result;
$result = 'hi there!';
return 'result';
}
echo <<<EOF
text ${hello()} text
EOF;
Technically, this works, but it's better to avoid hacks like this in production. A temporary variable will be much cleaner.

Since you cannot directly call a function inside HEREDOC, you may put the function name in a variable, and use that variable inside the HEREDOC string:
$showcaptcha= 'showcaptcha';
echo
<<<HTML
<br/> dawg {$showcaptcha()} dawg
HTML;
So you can leave the current already coded function:
function showcaptcha()
{
return "Gotta captcha mall";
}
You could also use:
$showcaptcha = function()
{
return "Gotta captcha mall";
}
echo
<<<HTML
<br/> dawg {$showcaptcha()} dawg
HTML;
If the function to call is defined at the same level as the echo (else, you'll have a global variable $showcaptcha).
If you have several functions, you can make a loop before the heredoc:
function dawg()
{
return "I'm loyal";
}
function cat()
{
return "I'm cute";
}
function fish()
{
return "I'm small";
}
function elephant()
{
return "I'm big";
}
$functionsToCall = array('elephant', 'fish', 'cat', 'dawg');
foreach ($functionsToCall as $functionToCall)
$$functionToCall = $functionToCall;
echo
<<<HTML
<br/> Dawg: {$dawg()}
<br/> Cat: {$cat()}
<br/> Fish: {$fish()}
<br/> Elephant: {$elephant()}
HTML;
That's way less ugly than using a global variable

No, it is not possible to use function inside heredoc strings.

Related

using a php variable inside of html using a jquery insertAfter

I've got a php function that is something like this
function get_some_info()
{
$location = other_function_that_returns_a_string();
return <<<HTML
<script>
$("<h1> <?php echo $location ?> </h1>").insertAfter("header");
</script>
HTML;
}
but I can't get my variable to dynamically display.
I've also tried something like this
$("<h1> <?php $location = other_function_that_returns_a_string() echo $location?> </h1>").insertAfter("header");
and it never displays anything dynamically. How can I get my variable to show up?
The issue is that you use the HEREDOC syntax.
You don't have to use <?php and ?> inside that.
This will work fine:
$("<h1> $location </h1>").insertAfter("header");
Here is the code I tested in PhpFiddle:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
Header
</header>
<?php
function other_function_that_returns_a_string(){
return "A string";
}
function get_some_info(){
$location = other_function_that_returns_a_string(); // Will be "A string"
return <<<HTML
<script>
$("<h1> $location </h1>").insertAfter("header");
</script>
HTML;
}
echo get_some_info();
?>

Get content of another PHP-File and use variables for current PHP-File

I want to use a variable inside an HTML-String of another PHP-File template.php in my PHP-File constructor.php.
I´m searched on Stackoverflow for a workaround to include the content of the other PHP-File. I included the following code into constructor.php because its known to be more safe instead of using file_get_contents(); Source:
function requireToVar($file){
ob_start();
require($file);
return ob_get_clean();
}
The rest of constructor.php looks like this:
...
$sqli = mysqli_query($mysqli, "SELECT ...");
if(mysqli_num_rows($sqli) > 0){
$ii = 0;
while ($row = $sqli->fetch_assoc()) {
$ii++;
if($row['dummy']=="Example"){
$content.=requireToVar('template.php');
...
The template.php looks like this:
<?php echo "
<div class='image-wrapper' id='dt-".$row['id']."' style='display: none;'>
...
</div>
"; ?>
The constructor.php doesn´t recognize the var $row['id'] inside the string of template.php as its own variable and also doesn´t execute it. The variable definitely works for the other code in constructor.php.
If I´m copy&paste the code of template.php into constructor.php after $content.= its working like a charm. But I want to restructure my constructor.php because its getting to big and this way its easier to customize.
I don´t know how to describe this problem more exactly, but I´m hoping this title fits to my problem.
Update your function
function requireToVar($file,$row_id){
ob_start();
require($file);
return ob_get_clean();
}
so you can call it like that
while ($row = $sqli->fetch_assoc()) {
$ii++;
if($row['dummy']=="Example"){
$content.=requireToVar('template.php',$row['id']);
and display it in template.php like that
<div class="image-wrapper" id="dt-<?php echo $row_id; ?>" style="display: none;"></div>
Use MVC model and renderer functions. For example: index.php
<!DOCTYPE HTML>
<html>
<head>
<title><?=$title; ?></title>
</head>
<body>
<h3><?=$text; ?></h3>
</body>
</html>
Than I'll have PHP array that contains those variables:
$array = array("title"=>"Mypage", "text"=>"Mytext");
Now we will use both in renderer function
function renderer($path, $array)
{
extract($array); // extract function turn keys into variables
include_once("$path.php");
}
renderer("index", $array);
Your approach is rather strange, but anyway; you can access $row from within $GLOBALS array.
Write your template as:
<?php echo "
<div class='image-wrapper' id='dt-".$GLOBALS['row']['id']."' style='display: none;'>
...
</div>
";
?>

Return HTML from PHP function

I have a PHP function that I'm using to output a standard block of HTML
<?php function test () { ?>
echo(" <html>
<body><h1> HELLO </h1> </body>
</html>
<?php } ?>
but i see the string of HTML and not the page
I have see this
Is there any way to return HTML in a PHP function? (without building the return value as a string)
if you use SLIM framework change the content type:
$app->contentType('application/json');
to:
$app->contentType('text/html');
then use render function of slim instance with specific template or simply echo html string
you have to do
<?php
function text() {
echo '<html><body><h1>Hello</h1></body></html>';
}
?>
But in addition this is not the base valid structure of a page. You're missing the <head /> tag.
Try this:
<?php
function test ()
{
echo '<html><body><h1> HELLO </h1> </body></html>' ;
}
?>
Try this:
<?php
function text() {
return '<html><body><h1>Hello</h1></body></html>';
}
?>
and where you need it just:
<?php echo text(); ?>
Try out this:
<?php
function test()
{
$html = '<html>';
$html .= '<body>';
$html .= '<h1>Hello</h1>';
$html .= '</body>';
$html .= '</html>';
echo $html;
//or
return $html;
}
?>
In PHP you have something called heredoc which lets you write large amounts of text from within PHP, but without the need to constantly escape things. The syntax is <<<EOT [text here] EOT;
So in your case you can have the function return the text like this
function test() {
return <<<EOT
<html>
<body><h1>HELLO</h1></body>
</html>
EOT;
}
Then just call function test to get the contents
echo test();

Codeigniter vars inside a view functions

I've a function inside a view (I've nested code so there is no alternative).
My problem is made because i want to add some vars inside the function.
I can't access to the var inside the function.
<div>
<?php _list($data); ?>
</div>
<?php
echo $pre; // Perfect, it works
function _list($data) {
global $pre;
foreach ($data as $row) {
echo $pre." ".$row['title']; // output ' title' without $pre var
if (isset($row['childrens']) && is_array($row['childrens'])) _list($row['childrens']);
}
}
?>
Simple... just define the function like this:
function _list($data, $pre=NULL)
then inside the function, you could check if the $pre is NULL then search for it somewhere else... using the global statement in functions is not desirable.
On the other hand you can define('pre',$pre); and use the pre constant created in your function... again not desirable but it would work for your example.
Later edit: DEFINE YOUR FUNCTIONS IN HELPERS
i am not sure why i forgot to suggest that in the first place
define function in view is weird. using global variable make it worse.
maybe you should avoid the global function with this:
<div>
<?php
foreach($data as $row){
_list($pre, $row);
}
?>
</div>
<?php
function _list($pre, $row) {
echo $pre." ".$row['title'];
if (isset($row['childrens']) && is_array($row['childrens'])){
foreach($row['childrens'] as $child){
_list($pre, $child);
}
}
}
?>
btw, define function in helpers would be better
http://ellislab.com/codeigniter/user-guide/general/helpers.html
whsh they help

content displaying out side of html tags for return and echo

I know that echo will echo the content and return will return the contents for further processing. How ever, I have said function:
class Content{
protected $_html = '';
public function display_content(){
$this->_html = 'content';
}
public function __toString(){
return $this->html;
}
}
then some where I have the following:
$content = new Content();
<p><?php $content->disaply_content(); ?></p>
I get:
<p></p>
content
as the source code for the page. doesn't matter if I echo or just return, either way it displays out side the tag.
Ideas?
I'm not sure where the second 'content' is coming from but note that:
<?php $content->display_content();?>
Will not display anything between the <p> tags. You should use:
<?php echo $content->display_content();?>
(I assume the disaply_content() was a typo in the question and not in the code).

Categories