一般对于Util方法,不外乎下面几种方法,以及我的一点看法:
PHP 5.4 引入了 Trait,一般来说,用它作为 Interface 的默认实现似乎受众比较多。
用 Trait 来导入 Util 函数肯定是可行的,但这种解决方法是否违背 OOP 原则?是否最佳或者“优雅”呢?我举个例子:
Trait FormatDatetimeTrait
{
proteted function formatDatetime($datetime, $style)
{
return date($style, $datetime);
}
}
好了,这个方法干的活儿似乎多余————这不是我们讨论的重点,这只是个例子。在其他类中使用这个 Trait:
Class FooBar
{
use FormatDatetimeTrait;
/** Other stuff **/
protected function getDate()
{
return $this->formatDatetime($this->time, $this->timeStyle);
}
}
我想这里 Trait 的引用还是有好处的:
那么,作为一种代码重用的工具,这么使用 Trait 都有那些缺点呢?是否违背 OOP 原则,或者违背它的设计初衷呢?
也欢迎有其他语言 Trait 使用经验的朋友提出宝贵意见 :-)。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
认证高级PHP讲师