Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return embedded non-php block as a `string`

    public function script(): string
    {
        ?>
            <script type="text/javascript">
                const foo = {
                    widgetcode: '<?= $this->widget_code() ?>',
                }
            </script>
            <?php
    }

This code works effectively, but as I’m moving a codebase to stricter standards (and I’m unfamiliar with php), how do I cast this return to a string? What is incorrect with this syntax? I’ve checked the php docs, but they are more focused on HEREDOC or NOWDOC, and this scripted code better lends itself to a non-php block with scriptlets like <?=.

How do I return this "script()" as a string?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you misunderstood how PHP returns code. When you call your function, your code is printed, but not returned.

To improve the readability of your code and to improve your PHP skills a bit, I split the original function into two separate. The script() function now retrieves the widget code, while the generateScript() function generates the JavaScript code.

The difference between RETURNING and PRINTING:

  • Printing: When you print the JavaScript code using echo or directly within the PHP tags (like you did with ?> and <?php). The output is sent directly to the browser – this means the JS code is immediately included in the HTML response that was sent to the client.

  • Returning: When you return the JS code as a string, the output is not immediately sent to the browser. Instead, it is returned to the caller of the function, which allows you to manipulate (or use the string further) before sending it to the browser.

I also used the HEREDOC syntax to make the JavaScript code more readable and maintainable by using multi-lines without the need for concatenation or escaping quotes.

public function script(): string
{
    $widgetCode = $this->widget_code();
    return $this->generateScript($widgetCode);
}

private function generateScript(string $widgetCode): string
{
    return <<<SCRIPT
    <script type="text/javascript">
        const foo = {
            widgetcode: '{$widgetCode}',
        }
    </script>
    SCRIPT;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading