简体   繁体   中英

Basic Inheritance in PHP Child & Parent Class

Okay, I may be just over complicating things in my head or just completely missing something; but I'm not too sure.

I have a class called Opportunity as well as a class called Activity.

An Opportunity will have many many Activities along with it.

There is no reason why an Activity needs to access Opportunity methods/properties as an activity is a one to many relationship between an opportunity and is a totally different object than an opportunity. But an Activity can not exist without being linked to an Opportunity.

Is this a child parent relationship or does Activity need to extend the Opportunity Class?

How does inheritance work with this example?

You are talking about the Composite pattern , your class Opportunity is composed by one or several Activities .

Is this a child parent relationship or does Activity need to extend the Opportunity Class?

Is not a child parent relationship because there is no hierarchy between them, Activities does not need to use or reimplement any Opportunity method nor attribute. Activities are simply a part of the Opportunity. So no, Activity does not need to extend the Opportunity Class.

You don't have to make them a parent - child relationship. In fact, if anything, it sounds like you need dependency injection instead

class Activity {
    /** @var \Opportunity */
    protected $opportunity;

    public function __construct(\Opportunity $opportunity) {
        $this->opportunity = $opportunity;
    }

    public function run() {
        $this->opportunity->doSomething();
    }
}
$activity = new \Activity($opportunity); // Pass an instance of Opportunity here

This way, you have to have your Opportunity class and Activity has access to it but it can only use the methods it needs . No worries about inheritance.

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