看來,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.
你運行'nested2。 php'與'nested1.php'分開嗎? – nosthertus