PHP - 在函数中定义类 [英] PHP - defining classes inside a function
问题描述
这是不好的做法吗?
like:
function boo(){
require_once("class.moo.php");
}
...
?
推荐答案
是这是不好的做法;
您可能会得到这两个答案,原因如下:
You're likely going to get both answers, and here's why:
如果使用 __ autoload
(或等价物),则调用:
If you use __autoload
(or equivalent), calling:
function someFunc()
{
$n = new UndefinedClassName();
}
等效于:
function someFunc()
{
include('path/to/UndefinedClassName.php');
//may be require_once, include_once, include, or require
//depending on how autoload is written
$n = new UndefinedClassName();
}
但是如果你避免使用 __ autoload
。为了保持你的代码,最好将所有包含
放在脚本的顶部,就像 import
But you'll get better performance out of your code if you avoid using __autoload
. And to maintain your code, it's better to put all your includes
at the top of the script like you would for import
statements in other languages.
include('path/to/UndefinedClassName.php');
...code...
function someFunc()
{
$n = new UndefinedClassName();
}
我建议一致性。如果你一直调用函数中的 include
,你不应该有太多的问题,但我会选择导入在文件的开头,或者 autoloads
。
I would suggest consistency. If you consistently call the include
in the functions, you shouldn't have too many issues, but I would choose imports at the beginnings of files, or as autoloads
.
这篇关于PHP - 在函数中定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!