簡體   English   中英

PHP - 在函數內定義類

[英]PHP - defining classes inside a function

這是一種不好的做法嗎?

喜歡:

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

是的,這是不好的做法; ,不是。

您可能會得到兩個答案,這就是原因:

如果您使用__autoload (或等效),請致電:

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您將從代碼中獲得更好的性能。 為了維護您的代碼,最好將所有includes放在腳本的頂部,就像使用其他語言的import語句一樣。

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

我會建議一致性。 如果你一直在函數中調用include ,你不應該有太多的問題,但我會選擇文件開頭的導入,或者作為autoloads

我會避免它。

這不是另一個開發人員所期望的,因此會降低代碼的可維護性。

這就是類加載器的工作方式。 這不一定是不好的做法。

取決於函數的功能以及執行此操作的原因。 使用自動加載可能更合適。

這通常是一種不好的做法,應該避免。 您應該考慮使用自動加載器

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM