【发布时间】:2011-02-22 14:14:13
【问题描述】:
这是我考虑了一段时间的事情。我想将一组方法链接在一起,如下所示的示例。
方法链的概念很简单,但我想要的是让我们所有的动物都通过相同的add 方法添加,那么我应该如何确定我们在add 中添加的动物类型方法?
$zoo = new Zoo;
$lion = $zoo->lion->add('Lucas the lion');
$cockatoo = $zoo->cockatoo->add('Chris the cockatoo');
class Zoo {
function add($name) {
//How to figure out if the animal is a Lion or an Cockatoo?
}
}
【问题讨论】:
-
为什么不
$zoo->add(new Lion('Lucas'));?在哪里class Lion implements IAnimal {} -
我无法忍受这样的束缚。我认为它完全破坏了可读性并使您的代码模棱两可。如果必须,我建议将其更改为:
$zoo->add(new Lion('Lucas the Lion'));它将 Lion 类与 Zoo 类分离,并让您更加灵活...... -
if($item instanceof Lion){ /* do something with lions */ } -
@thephpdeveloper :
$item起源于哪里? -
$item,假设你的参数$name改为$item
标签: php oop method-chaining