dongyanzhui0524 2012-01-26 22:06
浏览 135
已采纳

PHP:函数内的函数然后包含内部函数

I have tested the following and it doesn't work. Is there a similar way of achieving this?

A compiling class which formulates a template:

private function include_header () {
    function _metadata () {
        // Metadata compiler
        return $metadata;
    }
    include (path . "header.php");
}

header.php

<html>
<head>
    <?php
        _metadata ();
    ?>
    <title>Hello Stackoverflow!</title>
</head>
<body>
    ...

The _metadata (); function is only available within the include_header (); function - nowhere else in the class. I don't want to have to write $this->_metadata (); in the template file only _metadata ();. Is that achievable?

Alternatively one could create an external file, for example functions.php which has the underscore functions specifically for the template - but I'd much rather see if the original query is possible.

Thank you in advance.

  • 写回答

2条回答 默认 最新

  • dongruolin5324 2012-01-26 22:13
    关注

    From the manual:

    All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

    So, essentially, you can't do what you're trying to do. _metadata will always be a global function if it is defined with the function _metadata() { syntax. The normal function syntax only supports global functions.

    However, PHP 5.3 introduces something called "anonymous functions". These can be assigned to a variable. Since variables can be scoped to a function scope (they are only global if you explicitly say so), you can limit them in this way.

    For instance:

    $_metadata = function() {
        // Metadata compiler
        return $metadata;
    };
    

    This could then be called in header.php with:

    <?php $_metadata(); ?>
    

    Note that this is less stable: it is, for instance, possible to redefine the variable to be a different anonymous function – or indeed not a function at all. The safest solution, ultimately, is to use a templating language that solves these issues for you. If not, you can either accept that you'll have to use global functions or anonymous functions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择