如何使 PHP 函数等到脚本结束执行


how to make a php function wait to execute until the end of the script

我正在尝试为javascript文件创建一个队列函数。基本上,这就是我希望它工作的方式:我想创建一个函数,它将接收发送给它的所有 javascript 并将它们放在页面上的适当位置(即页眉或页脚,以及依赖脚本上方)。

我希望能够说:这是一个脚本。按其应加入的顺序将其添加到队列中。然后,在所有脚本排队后,运行函数以将它们写入页面。到目前为止,我的代码如下所示:

$scripts = array();
function enqueue_script($src="", $script_name="", $script_data="", 
 $script_dependencies=array(), $force_header=false, $additional_atts=array()){
    global $scripts;
    //run check for duplicates
    //run check for dependencies already in the variable
    //run checks to see if this script depends on other scripts
    //$scripts array is saved in increments of 10 to allow for up to 
    //9 dependants
    $i = count($scripts);
    $i = ($i*10)+10;
    $scripts[$i]['src'] = $src;
    $scripts[$i]['script_name'] = $script_name;
    $scripts[$i]['script_data'] = $script_data;
    $scripts[$i]['dependencies'] = $script_dependencies;
    $scripts[$i]['force_header'] = $force_header;
    $scripts[$i]['atts'] = $additional_atts;
}
function write_scripts_header() {
    global $scripts;
    $echo = "";
    $atts = "";
    //create script tag for insertion in header
    foreach($scripts as $s){
        if($s['force_header']){
            foreach($s['atts'] as $a => $v){
                $atts .= " {$a}='{$v}'";
            }
            if($s['src']!=""){
                $echo .= "<script src='{$s['src']}'{$atts}></script>'n";
            } else {
                $echo .= "<script{$atts}>{$s['script_data']}</script>'n";
            }
        }
    }
    echo $echo;     
}
function write_scripts_footer() {
    global $scripts;
    $echo = "";
    $atts = "";
    //create script tag for insertion in footer
    foreach($scripts as $s){
         if(!$s['force_header']){
            foreach($s['atts'] as $a => $v){
                $atts .= " {$a}='{$v}'";
            }
            if($s['src']!=""){
                $echo .= "<script src='{$s['src']}'{$atts}></script>'n";
            } else {
                $echo .= "<script{$atts}>{$s['script_data']}</script>'n";
            }
        }
    }
    echo $echo;
}

然后,在 HTML 文件部分中:

<html>
<head>
<?php write_scripts_header();?>
</head>
<body>
<?php write_scripts_footer();?>
</body>
</html>

如果最后加载 HTML 部分,则此方法可以正常工作。但是,如果我有一个包含在 body 标签的中间,并且该包含需要在标题中enqueue_script(),那么当 write_scripts_header() 函数运行时,$scripts变量还没有准备好。

如何write_scripts_header()write_scripts_footer()等到所有脚本都排队后再运行? 或者....有没有更好的方法来允许脚本队列,以便我可以在最后将所有脚本写入文档?

如果它都在同一个文件中运行,你能不能让正文内容成为一个变量,$body,先加载它,然后将其回显到<body>部分?

change
<html>
<head>
<?php write_scripts_header();?>
</head>
<body>
<?php write_scripts_footer();?>
</body>
</html>

print "<html><head>".write_scripts_header()."</head><body>".write_scripts_footer()."</body></html>";

尝试使用模板引擎,例如 Twig,您将能够在完成脚本数组准备后输出您的 html。