Search code examples
phphtmlfunctioninline-code

PHP Literal output with ?> in function definition


When writing PHP code in the past, I have often been plagued by the awkwardness of having to nest my HTML code in calls to print, echo or similar. This is alleviated to some degree by the ability to make parts of the code be literally outputted by closing the PHP tag and reopening it again after the output, eg:

<?php /*DoSomeStuff*/ ?>
Some HTML code.
<?php /*SomeMorePHP*/ ?>

However, I have never been clear on how this interracts with functions. For example, it is unclear to me if writing:

<?php
function myFunction() {
?>
Some HTML
<?php
}
?>

Will produce a function which upon being called will output that HTML, if the function will be parsed as empty but output that HTML during parsing, or neither, both or if this construct is just illegal entirely?

I am reluctant to base all my results on just trying this on some particular instance of PHP as I do not wish to beleive it works while in reality it might be undefined behaviour or think it doesnt work while I might just have an old or buggy PHP and I have never seen this construct used in any code.

Ideally I am looking for some kind of reference to documentation or specification which would clear this up.


Solution

  • I know this is not exactly answering your questions with a lot of references, but: This is valid (PHP Docs), although it doesn't look very nice, it's a common practice in some old but BIG frameworks.

    You can try this and see what happens:

    function htmlOut() {
        ?>
        Some HTML output
        <?php
    }
    
    
    htmlOut();
    

    By the way I found an example, the default skin of MediaWiki (I would say they know what they are doing) is using just the method you have described.

    /**
     * Outputs the entire contents of the (X)HTML page
     */
    public function execute() {
        /**
         * some code
         */
        // Output HTML Page
        $this->html( 'headelement' );
        ?>
        <div id="mw-page-base" class="noprint"></div>
        <div id="mw-head-base" class="noprint"></div>
        <div id="content" class="mw-body" role="main">
            <a id="top"></a>
    
            <?php
        /**
         * some more code
         */
    }
    

    See the full code here: MediaWiki GitHub