dornc9470 2018-07-23 21:01
浏览 30
已采纳

too long

So maybe I'm just having a brain hiccup, idk. But it seems like this should work but it doesn't.

The Intent

Build a string throughout a page for use later on in the app page.

The Question

How do we store a string in a way that we can add to it with a function several times before using the resulting value of the string? Is there a better way to do this with a function than to use a variable?

A Non-Working Example

<?php
$testNG = "";
function testNG($tng){
  $testNG .= $tng;
  return $testNG;
}
testNG("hello!!");
?>
<h2><?= $testNG; ?></h2>

As always, thank you all for contributing to making the online world a much more efficient place!

Edit

An example purpose for this would be to allow Javascript to be aggregated into a variable so that it can be created near the elements it effects, then placed in a section before the </body>

<div id="rating"></div>
<?php testNG("$('#rating').rating();"); ?>
<p>blah blah</p>
...

...
</footer>
<?php
if($testNG != ""): ?>
<script>
<?= $testNG; ?>
</script>
<?php endif; ?>
  • 写回答

4条回答 默认 最新

  • douhuan1901 2018-07-23 21:20
    关注

    One way to do it is to declare $testNG as static within your function rather than using a global variable. From the PHP manual:

    A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

    So each time you call the function it will add the input to whatever's already there.

    <?php
    
    function testNG($tng = '') {
        static $testNG = '';
        return $testNG .= $tng;
    }
    
    testNG("hello!!");
    testNG(" world!!");
    testNG(" etc.");
    ?>
    <h2><?= testNG(); ?></h2>
    

    Demo at 3v4l.org

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境