繁体   English   中英

将值从“调用PHP”脚本传递到“调用PHP”脚本

[英]Passing Values from Calling PHP script to Called PHP script

所以我有这个页面构建器类:

<?php
class PageBuilderService {
    public function getHeader() {
        // return file_get_contents('template/header.html');
        include 'template/header.php';
    }

    public function getFooter() {
        return file_get_contents('template/footer.html');
    }
}
?>

在PHP页面中,其调用方式如下:

$page_builder = new PageBuilderService();

然后我要在何处调用页面标题:

$page_builder->getHeader();

等等

但是我想添加一个脚本函数,该函数将scripts.php一个scripts.php文件,该文件将遍历传递给它的脚本文件名列表,以便在页面上显示<script>标签。

Scipts php文件:

<?php
    $page_builder = new PageBuilderService();

    echo $page_builder::createScriptTags($listOfScripts);
?>

因此,显然这意味着扩展了我的PageBuilderService类:

<?php
class PageBuilderService {
    public function getHeader() {
        // return file_get_contents('template/header.html');
        include 'template/header.php';
    }

    public function getFooter() {
        return file_get_contents('template/footer.html');
    }

    public function getScripts() {

            include 'template/scripts.php'; // Maybe here the list of scripts can be injected?
    }

    public static function createScriptTags($listOfScripts) {
        $scriptHtml = "";
        foreach ($listOfScripts as $script) {
            // some html building
        }

        return $scriptHtml;
    }
}
?>

从PHP页面将$listOfScripts获取到脚本php文件的最佳方法是什么?

$_GLOBAL[]这样的方法是最好的方法吗?

结果将是这样的:

$page_builder->getScripts(); // and some way of getting a list of scripts to the script page

理想情况下,我想:

$scriptsToInclude = array("neededJsFile.js", "someOtherJs.js");
echo $page_builder->getScripts($scriptsToInclude);

但是显然,这取决于可能的情况。

怎么样 :

class PageBuilderService {
    private $aScripts = array();        

    public function addScript($cScript) {
        $this->aScripts[$cScript] = true;
    }

    public static function createScriptTags() {
        $scriptHtml = "";
        foreach ($this->aScripts as $script) {
            // some html building
        }

        return $scriptHtml;
    }
}

这样,您可以根据代码动态添加不同数量的脚本,但是当您调用createScriptTags时,它们都会全部注入...还是我遗漏了真正的问题?

就像@DragonYen所说的,在脚本a中设置一个变量,然后调用脚本b并访问该变量即可。 因此,我将创建一个包含以下内容的脚本数组

$scriptsToInclude = array("script1.js", "script2.js");

然后调用脚本php

echo $page_builder->getScripts();

然后在脚本php中,检查脚本的$scriptsToInclude变量并构建是否有任何变量

if (!empty($scriptsToInclude) && count($scriptsToInclude) > 0) {
   PageBulderService::createScriptTags($scriptsToInclude);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM