将变量用于多个输出?[PHP函数]


Use variables for more than one output? [ PHP Functions ]

我目前是一名初级开发人员,在业余时间刚刚开始我的第一个大项目,我想做的基本上是将变量写入html/tpl文档,我目前正在处理,这是我的代码:

private function index(){
    $username = 'MyUsername';
    $onlineTime = 'MyOnlineTime';
    $this->setParams('Username', $username); // $username Will be replaced by database queried results once completed.
}

这是setParams函数。

function setParams($item1, $item2){
    ob_start();
    $theme = 'default';
    include_once T . '/'.$theme.'/index.php';   // T . is defined at the beginning of the document.
    if ((($html = ob_get_clean()) !==  false) && (ob_start() === true))
    {
    echo preg_replace('~{(['.$item1.']*)}~i', ''.$item2.'', $html, 1);
    }
    }

这是html/tpl文档中的编码。

{username} has been online for {onlineTime} Hours

对于你们中的一些人来说,这可能是一个非常简单的代码,但由于这是我的第一次尝试,这是我所能做的

我想做的是拥有它,这样你就可以随心所欲地设置Params,而无需更改$variable名称,比如:

private function index(){
    $username = 'MyUsername';
    $onlineTime = 'MyOnlineTime';
    $this->setParams('Username',$username);
    $this->setParams('OnlineTime', $onlineTime);
}

同时保持setParams($item1, $item2)

但正如你所能想象的那样,这只是完全削减了代码。有人知道这个问题的解决办法吗?我找了一整天都没有什么运气。

提前感谢

Ralph

我认为您需要的是一个具有静态方法的类;

<?php
class Params {
    public static $params = array();
    public static function setParam($key, $value) {
        self::$params[$key] = $value;
    }
    public static function getParam($key) {
        if (isset(self::$params[$key])) {
            return self::$params[$key];
        }
    }
}
// Usage
// Set Username
Params::setParam("username", "JohnDoe");
Params::setParam("password", "12345");
echo Params::getParam("username");
echo Params::getParam("password");