[英]How access the member functions of a child class in another child class of same parent
我有三個類,可以說Class A , Class B和Class C B。
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?
public class A {
}
class B extends A{
public function hello (){
return "Hello world";
}
}
public class C extends A{
public function world (){
$this->hello();
}
}
擴展@u_mulder 的評論:這確實是不可能的,因為盡管 B 和 C 都派生自同一個 class A,但它們是不同的類,就像自行車和汽車都是車輛一樣。 使用自行車時,您不能假設使用汽車的功能,僅僅因為它們都是車輛。
您需要自己回答的問題是我在class B
中需要的方法的功能是什么? 它是否特定於class B
? 還是所有實體都是class A
? 或者不同的是,它是否完全是一個單獨的功能,但只有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
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.