nowdoc inside a function

63
August 12, 2018, at 08:30 AM

I have some PHP code that I want to convert to a function. Unfortunately the code uses nowdoc to create a format string for a sprintf() call. This poses a formatting dilemma because It means I can't indent the closing identifier to match the function layout. The nowdoc is an HTML snippet so I could remove all line breaks and treat it as a simple string variable, but that makes the code more difficult to read. Another way would be to create the format string in global scope using nowdoc, and passing the resulting string to the function. Is there any way to use nowdoc and keep my normal formatting style?

Answer 1

As mentioned in my comment, if you want to keep your formatting on both pages, just use include():

/string.php

<?php
$str = <<<'EOD'
This is a string
EOD;
// This line after "EOD;" needs something on it or it may throw this error:
// Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or heredoc end (T_END_HEREDOC) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN)

/myfunction.php

<?php
function myfunction()
{
    # Include the nowdoc file
    include(__DIR__.'/string.php');
    # Return the string back
    return $str;
}
READ ALSO
Wordpress add_rewrite_rule not working - 404 not found error

Wordpress add_rewrite_rule not working - 404 not found error

I know there are a lot of topic about this but I could't find any solution to my problem

83
cookie counter increases dramatically after 2 counts

cookie counter increases dramatically after 2 counts

I have this php code in a serversIt receives a post request and deals with the data

53
Yii2 - compress cookie value or better alternative

Yii2 - compress cookie value or better alternative

I am dealing with a existing code which stores the order item details in a cookie

97
Laravel5.6(PHP Powerful framework) [on hold]

Laravel5.6(PHP Powerful framework) [on hold]

I am working on a project using laravel 56

64