函数内声明函数的范围 [英] Scope of declared function within a function

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

问题描述

我想知道为什么在类函数中声明函数时,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.

例如:

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.

问候.

推荐答案

在 PHP 中,所有函数始终是全局的,无论您如何或何时定义它们.(匿名函数是部分例外.)因此,您的两个函数定义都将是全局的.

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.

来自文档:

PHP 中的所有函数和类都具有全局作用域 - 它们甚至可以在函数外部调用如果它们是在内部定义的,反之亦然.

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天全站免登陆