Search code examples
phpnowdoc

nowdoc inside a function


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?


Solution

  • 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;
    }