简体   繁体   中英

Class method naming issues - conflicts with extended class?

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 eg 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, eg $this->Account->create(); .

Is there another way, eg 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!

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

No, this is not naturally, you are misusing inheritance. Or would you say that an associate is an account? If it has an account, use composition. If not, but the account class has methods that are useful for the associate class, they probably shouldn't be in the account class at all. Extract them to one or more other classes which can be used by both, Account and Associate.

The child class method will be called using $this if you are within the child class methods. If you want the parent method though, you'd call parent::create(); from within the child method.

But that is if you absolutely need to extend the Account class, which sounds unnecessary. If the "Account" class has public methods then you don't need to extend it, you can just call them after instantiating the class:

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

Or, if it is a public static method:

$creation = Account::create();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM