2

This is less of an issue, and more of a best practice question - I know these are subject to opinion, but I'm sure there must be a standard convention for this particular problem.

Let's say I've got two classes, Account and Associate.

Account contains several methods which are useful to Associate, and so naturally I'd extend the Account class to Associate.

However, an issue of course arises when I have two methods with the same name e.g. create().

So far to counteract this instead of extending the parent class, I've been instantiating it as a variable in the child classes __construct() method, and then calling methods through that, e.g. $this->Account->create();.

Is there another way, e.g. a norm for using an extended classes methods while still having a method of the same name in the child class?

Any answers would be greatly appreciated!

4

2 回答 2

1

Account 包含几个对 Associate 有用的方法,因此我很自然地将 Account 类扩展为 Associate。

不,这不是自然的,你在滥用继承。或者你会说一个同事是一个帐户?如果它帐户,请使用组合。如果不是,但帐户类具有对关联类有用的方法,它们可能根本不应该在帐户类中。将它们提取到一个或多个其他类,Account 和 Associate 都可以使用。

于 2013-02-25T08:05:51.203 回答
0

$this如果您在子类方法中,则将调用子类方法。但是,如果您想要父方法,则可以parent::create();从子方法中调用。

但那是如果您绝对需要扩展 Account 类,这听起来没有必要。如果“Account”类有公共方法,那么你不需要扩展它,你可以在实例化类之后调用它们:

$account = new Account();
$account->create();

或者,如果它是一个公共静态方法:

$creation = Account::create();
于 2013-02-25T07:25:38.327 回答