2017-03-18 32 views
1

看來,PHP通常需要在使用前被定義嵌套函數。但隨着require動態生成的代碼不具有相同的限制。任何人都可以解釋爲什麼不一致?爲什麼這些PHP嵌套函數的例子不同的表現?

編輯:只是爲了澄清,我想了解的是:爲什麼例2的工作,而不是失敗例子1相似?

例1

如果這是文件nested1.php的內容:

<?php 
function outer() { 
    inner(); 
    function inner() { 
     print "Hello world.\n"; 
    } 
} 
outer(); 
?> 

php nested1.php回報運行此:

PHP Fatal error: Call to undefined function inner() in nested1.php on line 3

但是,如果移動inner()功能在函數定義下面調用,如下所示:

<?php 
function outer() { 
    function inner() { 
     print "Hello world.\n"; 
    } 
    inner(); 
} 
outer(); 
?> 

,並再次運行你:

Hello world.

例2

如果這是nested2.php內容:

<?php 
function outer() { 
    require "inner.php"; 
} 
outer(); 
?> 

這是inner.php內容:

<?php 
    inner(); 
    function inner() { 
     print "Hello world.\n"; 
    } 
?> 

php nested2.php返回運行此:

Hello world.

+0

你運行'nested2。 php'與'nested1.php'分開嗎? – nosthertus

回答

2

實施例1: PHP does not support nested functions. It only supports inner functions. Nested function reference

Inner function reference

<?php 
function outer() { 
    inner(); 
    function inner() { 
     print "Hello world.\n"; 
    } 
} 
outer(); 

例2:In this function you are just requiring file which includes and evaluates the scripts.Reference

<?php 
function outer() { 
    require "inner.php"; 
} 
outer(); 
?> 

<?php 
    inner(); 
    function inner() { 
     print "Hello world.\n"; 
    } 
?> 
+0

我不同意; PHP確實支持嵌套函數。編輯我的問題來澄清。 – Kruthers

+0

@Kruthers在你的'Example 1'中根據你的PHP代碼的第一部分,你在定義之前調用函數。如果PHP支持嵌套函數,它將被訪問。但在第二部分中,您可以在定義後調用函數。這是'內部函數'所述。我正在更新我的答案與嵌套函數和內部函數的參考 –

+0

@SahilGulati好的謝謝澄清。所以術語「嵌套」意味着PHP在這種情況下實際上沒有做的具體事情。但是您提供的鏈接並不能幫助我理解爲什麼示例2的工作方式不同。例如,inner.php可以訪問require語句前的outer()中定義的變量。所以PHP在導入之前不能評估inner.php。它看起來應該像例子1一樣行事(至少在我微薄的理解中......) – Kruthers

0

在你的第一個例子中,你正試圖定義另一個函數內一個新的功能,但嵌套函數沒有被允許PHP。做這樣的事情會很好:

<?php 
function outer() { 
    inner(); 
} 
outer(); 
function inner() { 
    print "Hello world.\n"; 
} 
?> 

在你的第二個例子中,你包含一個文件。由於您在inner.php中未使用嵌套函數,因此代碼可按預期工作。

+0

PHP確實支持嵌套函數。查看編輯的問題。 – Kruthers

2

當第一次調用outer()函數時,其中的inner()函數將在全局範圍內聲明。

function outer() { 
    function inner() { 
     print "Hello world.\n"; 
    } 
    inner(); 
} 
outer(); 
outer();//Second call 

因此,你會得到以下錯誤:

Fatal error: Cannot redeclare inner() 

因爲outer()第二個呼叫試圖重新申報inner()功能。

爲了避免這個問題,你需要使用匿名函數的聲明類似如下:

function outer() { 

    $inner = function() { 
     print "Hello world.\n"; 
    }; 

    $inner(); 
} 
outer(); 
outer(); 

在這種情況下$inner僅適用於本地功能「外」範圍

+0

感謝您的信息,但這並不回答我問的問題。 – Kruthers

相關問題