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
It should be like this
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 thegenerateScript()
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.