[英]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? 这是孩子的父母关系吗?Activity是否需要扩展商机类别?
How does inheritance work with this example? 此示例如何继承?
You are talking about the Composite pattern
, your class Opportunity
is composed by one or several Activities
. 您正在谈论
Composite pattern
,您的Opportunity
类是由一个或多个Activities
组成的。
Is this a child parent relationship or does Activity need to extend the Opportunity Class?
这是孩子的父母关系吗?Activity是否需要扩展商机类别?
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
不需要使用或重新实现任何Opportunity
方法或属性。 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 . 这样,您必须拥有
Opportunity
类,并且Activity
可以访问它, 但是它只能使用所需的方法 。 No worries about inheritance. 不用担心继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.