简体   繁体   English

PHP - 在函数内定义类

[英]PHP - defining classes inside a function

Is this a bad practice? 这是一种不好的做法吗?

like: 喜欢:

function boo(){
  require_once("class.moo.php");
}
...

?

Yes it is bad practice; 是的,这是不好的做法; no it's not. ,不是。

You're likely going to get both answers, and here's why: 您可能会得到两个答案,这就是原因:

If you use __autoload (or equivalent), calling: 如果您使用__autoload (或等效),请致电:

function someFunc()
{
  $n = new UndefinedClassName();
}

is equivalent to: 相当于:

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();
}

But you'll get better performance out of your code if you avoid using __autoload . 但是,如果您避免使用__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. 为了维护您的代码,最好将所有includes放在脚本的顶部,就像使用其他语言的import语句一样。

include('path/to/UndefinedClassName.php');
...code...
function someFunc()
{
  $n = new UndefinedClassName();
}

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 . 如果你一直在函数中调用include ,你不应该有太多的问题,但我会选择文件开头的导入,或者作为autoloads

I would avoid it. 我会避免它。

It is not what another developer would expect, and, as such, would reduce the maintainability of your code. 这不是另一个开发人员所期望的,因此会降低代码的可维护性。

This is how class loaders work. 这就是类加载器的工作方式。 This is not necessarily bad practice. 这不一定是不好的做法。

Depends on what the function does and why you are doing this. 取决于函数的功能以及执行此操作的原因。 Using autoloading may be more appropriate. 使用自动加载可能更合适。

This is generally a bad practice and should be avoided. 这通常是一种不好的做法,应该避免。 You should probably consider using an autoloader instead. 您应该考虑使用自动加载器

如果你有理由我没有看到任何不好的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM