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条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3