用traits还是继承扩展PHP库?
作为一名软件开发人员,我想为我的客户提供一个扩展库。不应更改库提供程序的原始库 有几种方法可以做到这一点。性格在脑海中浮现,但遗传也在脑海中浮现 假设原始库中有一个类定义为:用traits还是继承扩展PHP库?,php,inheritance,architecture,traits,Php,Inheritance,Architecture,Traits,作为一名软件开发人员,我想为我的客户提供一个扩展库。不应更改库提供程序的原始库 有几种方法可以做到这一点。性格在脑海中浮现,但遗传也在脑海中浮现 假设原始库中有一个类定义为: class Super {} 第一种方法:使用traits扩展原始库: trait MyTrait { public function func() { echo "func in MyTrait\n"; } } // Customer writes in his code: class
class Super {}
第一种方法:使用traits扩展原始库:
trait MyTrait {
public function func() {
echo "func in MyTrait\n";
}
}
// Customer writes in his code:
class Sub1 extends Super {
use MyTrait;
}
$sub1 = new Sub1;
$sub1->func();
第二种方法:使用继承扩展原始库:
class LibExtension extends Super {
public function func() {
echo "func in LibExtension\n";
}
}
// Customer writes in his code:
class Sub2 extends LibExtension {
}
$sub2 = new Sub2;
$sub2->func();
在这个场景中使用traits和heritace有什么优势?
哪种方法在哪种情况下更有限?作为软件开发人员或客户,哪一个给了我更大的灵活性
如果我们在开源领域或封闭源代码领域,这些方法有什么不同吗
对于这种情况,有更好的方法吗?很难推荐某种方法而不是另一种方法,但在许多情况下,组合是向最终用户提供灵活性的更合适的方法 考虑到你的特质样本:
trait MyTrait {
public function func() {
echo "func in MyTrait\n";
}
}
// Customer writes in his code:
class Sub1 extends Super {
use MyTrait;
}
$sub1 = new Sub1;
$sub1->func();
可以将其改写为:
interface FuncPrinterInterface
{
public function funcPrint();
}
class FuncPrinter implements FuncPrinterInterface
{
public function funcPrint()
{
echo "func in MyTrait\n";
}
}
class UserClass
{
/**
* @var FuncPrinterInterface
*/
protected $printer;
/**
* Sub1 constructor.
*
* @param FuncPrinterInterface $printer
*/
public function __construct(FuncPrinterInterface $printer)
{
$this->printer = $printer;
}
public function doSomething()
{
$this->printer->funcPrint();
}
}
$sub1 = new UserClass(new FuncPrinter());
$sub1->doSomething();