简体   繁体   English

如何在同一个父级的另一个子级 class 中访问子级 class 的成员函数

[英]How access the member functions of a child class in another child class of same parent

I've three classes lets say Class A , Class B and Class C .我有三个类,可以说Class AClass BClass C B。

Class A is parent class and class B and C are its child. Class A 是父 class 和 class B 和 C 是它的孩子。

There is function in class B, I want to access that function in class C without inheriting Class C with B. Is it possible? There is function in class B, I want to access that function in class C without inheriting Class C with B. Is it possible?

public class A {


}

class B extends A{

      public function hello (){
        return "Hello world";
      }
}

public class C extends A{

    public function world (){
        $this->hello();
    } 

} 

To expand upon @u_mulder's comment: it's indeed not possible, because though B and C both derive from the same class A, they are distinct classes, in the same way that a bicycle and a car are both vehicles.扩展@u_mulder 的评论:这确实是不可能的,因为尽管 B 和 C 都派生自同一个 class A,但它们是不同的类,就像自行车和汽车都是车辆一样。 When using a bicycle you cannot assume to use functions from a car, simply because they're both vehicles.使用自行车时,您不能假设使用汽车的功能,仅仅因为它们都是车辆。

The question you'd need to answer yourself is what is the functionality of the method I need in class B ?您需要自己回答的问题是我在class B中需要的方法的功能是什么? Is it specific to class B ?它是否特定于class B Or is it something all entities which are class A ?还是所有实体都是class A Or different yet, is it a separately functionality altogether but which only class B needs to consume?或者不同的是,它是否完全是一个单独的功能,但只有class B需要使用? The solution to the first case would be to move the function to class B .第一种情况的解决方案是将 function 移动到class B In the second case you'd move the function to class A. In the third case you'd implement the function in a separate class and inject that into class B . In the second case you'd move the function to class A. In the third case you'd implement the function in a separate class and inject that into class B .

I recommend you read up on SOLID principles and other principles of OOP design我建议您阅读OOP 设计的SOLID原则和其他原则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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