函数中声明函数的作用域 [英] Scope of declared function within a function

查看:110
本文介绍了函数中声明函数的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想知道为什么php在一个函数中处理一个声明函数的范围不同。

例如:

  function test()//全局函数
{
function myTest()//全局函数。为什么?
{
print(Hello world);
}
}

class CMyTestClass
{
public function test()// CMyTestClass的方法
{
function myTest ()//这个声明将是全局的!为什么?
{
print(Hello world);
}
}
}

}

任何人可以向我解释为什么会发生这种情况?
谢谢您的回答。



Greetz。

解决方案

在PHP中,所有函数总是全局的,无论如何或何时定义它们。



从文档


PHP中的所有函数和类全局范围 - 它们可以在函数之外调用,即使
,如果它们被定义在内部,反之亦然。



I was wondering why php handles the scope of a declared function within a function differently when a function is declared inside a class function.

For example:

function test() // global function
{
  function myTest() // global function. Why?
  {
    print( "Hello world" );
  } 
}

class CMyTestClass
{
  public function test() // method of CMyTestClass
  {
    function myTest() // This declaration will be global! Why?
    {
      print( "Hello world" );
    } 
  }
}

}

Can anybody explain this to me why this happen? Thank you for your answer.

Greetz.

解决方案

In PHP all functions are always global, no matter how or when you define them. (Anonymous functions are partially an exception to this.) Both your function definitions will thus be global.

From the documentation:

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.

这篇关于函数中声明函数的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆