什么是PHP嵌套函数? [英] What are PHP nested functions for?

查看:89
本文介绍了什么是PHP嵌套函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,嵌套函数非常有用:闭包,私有方法以及您拥有的东西.

In JavaScript nested functions are very useful: closures, private methods and what have you..

什么是嵌套PHP函数?有人使用它们吗?用于什么用途?

What are nested PHP functions for? Does anyone use them and what for?

这是我做过的小调查

<?php
function outer( $msg ) {
    function inner( $msg ) {
        echo 'inner: '.$msg.' ';
    }
    echo 'outer: '.$msg.' ';
    inner( $msg );
}

inner( 'test1' );  // Fatal error:  Call to undefined function inner()
outer( 'test2' );  // outer: test2 inner: test2
inner( 'test3' );  // inner: test3
outer( 'test4' );  // Fatal error:  Cannot redeclare inner()

推荐答案

基本上没有,我一直将其视为解析器的副作用.

There is none basically, I've always treated this as a side effect of the parser.

Eran Galperin误认为这些功能是某种私有的,只是在运行outer()之前才声明它们.它们也不是私有范围的,尽管确实延迟了,但它们确实污染了全球范围.作为回调,外部回调仍然只能被调用一次.我仍然看不到将其应用于很可能多次调用别名的数组上有什么帮助.

Eran Galperin is mistaken that these functions are somehow private, they are simply undeclared until outer() is run. They are also not privately scoped, they do polute the global scope albeit delayed. And as a callback the outer callback could still only be called once. I still don't see how that's helpful applying it on an array which very likely calls the alias more than once.

我可以挖掘的唯一真实世界"示例是只能运行一次,并且可以重写为更干净的IMO.

The only 'real world' example I could dig up is this which can only run once and could be rewritten cleaner IMO.

我唯一想到的用途是让模块调用[name] _include方法,该方法结合

The only use I can think of is for modules to call a [name]_include method which sets several nested methods in the global space combined with

if (!function_exists ('somefunc')) {
  function somefunc() { }
}

检查.

PHP的OOP显然是一个更好的选择:)

PHP's OOP would obviously be a better choice :)

这篇关于什么是PHP嵌套函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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