在 PHP 中使用 call_user_func 创建元素


Create element using call_user_func in PHP

我有一个PHP的东西,它使用call_user_func为放置的某个函数创建元素/对象。

示例函数.php 文件:


    function head($args=null){
       echo $args;
    }
    function footer($args=null){
       echo $args;
    }
    function createHeadTexts(){
       echo 'This is header area';
    }
    function createFooterTexts(){
       echo 'This is footer area';
    }
    //function to call this elements
    function addParam($arg, $val){
       call_user_func($arg, call_user_func($val));
    }

示例索引.php文件:


    head()
    This is contents area...
    footer()

回到我的函数.php文件,我添加了一个对函数的调用,即


addParam('head','createHeadTexts')//which is I thought has to be added on a header area.
addParam('footer','createHeadTexts')//which is I thought has to be added on a footer area too.

但是当我尝试查看我的PHP页面时,我遇到了一个问题。

它看起来像这样:


This is header area This is footer area 
This is contents area...

我认为文本应该像这样显示:


This is header area 
This is contents area...
This is footer area

唯一的函数应该放在我的索引中.php文件是 head() 和 footer()。head() 应该出现在 web 内容之前,footer() 应该出现在内容之后。

如果我想创建一个元素/对象/脚本到 head(),它应该是 addParam('head','创建元素/对象/脚本的函数');

请帮助我如何解决此问题,或者除了call_user_func之外还有其他方法吗?

谢谢

我刚刚测试了这个,结果很好:

<?php
function head($args=null){
    echo $args;
}
function footer($args=null){
    echo $args;
}
function createHeadTexts(){
    echo 'This is header area';
}
function createFooterTexts(){
    echo 'This is footer area';
}
// function to call this elements
function addParam($arg, $val){
    call_user_func($arg, call_user_func($val));
}
addParam('head','createHeadTexts');
echo '<br />This is contents area...<br />';
addParam('footer','createFooterTexts');
?>

和输出:

This is header area
This is contents area...
This is footer area

也许你忘了改变一些论点?我唯一改变的是

addParam('footer','createHeadTexts') to addParam('footer','create FOOTER Texts')