skip to Main Content
    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?

2

Answers


  1. It should be like this

    public function script(): string {
    
        $string = "
          <script type='text/javascript'>
            const foo = {
              widgetcode: ".$this->widget_code().",
            }
          </script>";
        return $string;
    }
    
    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search