PHP 中包含的文件出现致命的未定义函数错误
Fatal Undefined Function Error with included files in PHP
这是 PHP 手册中的声明:
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
我有一个名为 inc.php
的文件,其函数定义如下:
function echo_name($name) {
echo $name;
}
另一个名为 main.php
的文件具有以下代码(版本 1):
// This call throws an error
echo_name('Amanda');
require_once("inc.php");
// This call works
echo_name('James');
如果不使用 require_once
,我直接将函数所有调用工作(版本 2):
// This call works
echo_name('Amanda');
function echo_name($name) {
echo $name;
}
// This call works
echo_name('James');
PHP 手册中的
是什么意思
all functions and classes defined in the included file have the global scope.
当版本 1 中的代码失败但版本 2 有效时?
谢谢。
PHP 是一种解释型语言,意味着(删除所有当前不需要的细节)PHP 将主要逐行解释您的代码。
函数,class 声明在实际代码执行之前(在预编译阶段)被解释,但 require 和 include 指令仅在它们真正在代码中调用时才执行。
在您的第一个示例中,echo_name 函数不会在 require 语句之前声明,这就是您收到此错误的原因。
这是 PHP 手册中的声明:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
我有一个名为 inc.php
的文件,其函数定义如下:
function echo_name($name) {
echo $name;
}
另一个名为 main.php
的文件具有以下代码(版本 1):
// This call throws an error
echo_name('Amanda');
require_once("inc.php");
// This call works
echo_name('James');
如果不使用 require_once
,我直接将函数所有调用工作(版本 2):
// This call works
echo_name('Amanda');
function echo_name($name) {
echo $name;
}
// This call works
echo_name('James');
PHP 手册中的
是什么意思all functions and classes defined in the included file have the global scope.
当版本 1 中的代码失败但版本 2 有效时?
谢谢。
PHP 是一种解释型语言,意味着(删除所有当前不需要的细节)PHP 将主要逐行解释您的代码。 函数,class 声明在实际代码执行之前(在预编译阶段)被解释,但 require 和 include 指令仅在它们真正在代码中调用时才执行。
在您的第一个示例中,echo_name 函数不会在 require 语句之前声明,这就是您收到此错误的原因。