dongmu6225 2014-05-19 18:12
浏览 61
已采纳

PHP函数作用域调用函数内的函数[关闭]

I couldn't find anything regarding my issue while searching. Maybe I wasn't wording my search properly. Anyway, I the am trying to call a function from another file from inside another function, but it isn't working. It appears to be a scope issue. I have the following:

File1.php:

<?
function myCoolFunction()
{
    // Some really cool stuff in here
}

Then in File2.php:

<?
require('File1.php');

// A bunch of stuff

function anotherCoolFunction()
{
    // Do some stuff

    myCoolFunction();
}

myCoolFunction does not exist inside of anotherCoolFunction. I can call it in File2.php but not within another function. So my question is, how can this be achieved? Is there such thing as a super global function in php?

Thanks for any help!

  • 写回答

3条回答 默认 最新

  • douyi0219 2014-05-19 18:20
    关注

    For starters, use the function keyword to define functions.

    When you require a file in the way that you are you are bringing its contents into the scope of the file you are in. (Files within a namespace are a different story.)

    Think of your File2.php:

    <?
    require('File1.php');
    
    // A bunch of stuff
    
    function anotherCoolFunction()
    {
        // Do some stuff
    
        myCoolFunction();
    }
    

    The same thing as doing:

    <?
    function myCoolFunction()
    {
        // Some really cool stuff in here
    }
    
    // A bunch of stuff
    
    function anotherCoolFunction()
    {
        // Do some stuff
    
        myCoolFunction();
    }
    

    Lastly, (and I only say this because I don't see it in your code) make sure you call the encapsulating function. E.g.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?