【发布时间】:2012-01-12 09:44:15
【问题描述】:
我正在尝试确定是否适合使用一个类来声明一组约 20 个公共函数:
if (!class_exists('example')) {
class example {
# Declare ~20 functions (methods), all of
# which are public. (There's nothing else
# in the class.)
public static function one() { /* ... */ }
public static function two() { /* ... */ }
# ...
} # class
}
使方法可用:
example::one();
example::two();
上述方法 vs 有什么优点/缺点。只需这样做:
if (!defined('EXAMPLE_LOADED')) {
define('EXAMPLE_LOADED', true);
function example_one() { /* ... */ }
function example_two() { /* ... */ }
# ...
}
使功能可用:
example_one();
example_two();
EDIT - 相关性能测试:
【问题讨论】:
-
如果使用足够高的 PHP 版本,你也可以命名它们。
-
您很可能不应该为此使用类。类不应用作任意函数的“容器”。
-
namespaces 可能会更好地为您服务 - 这取决于您使用的 PHP 版本。
-
@TimG/Peter/Felix - 非常感谢 - 我正在阅读有关命名空间的信息。我猜他们只有5.3+。因此,如果我将其命名为
example,那么这些函数将可以作为example::one等使用,对吧? -
我还不会为 WP 插件使用命名空间 - 我认为 5.3 仍然太新,即使它仍然有 2 年多的历史。 WordPress'requirements 声明 PHP 版本 5.2.4 或更高版本,我会坚持下去。