简体   繁体   English

从父类创建对象并从子类调用类

[英]Creating object from parent class and call class from child class

I have one class created but is huge and has to many methodes.我创建了一个类,但它很大并且有很多方法。 I want to slice to separate child classes.我想切片以分隔子类。

I attempt something like this:我尝试这样的事情:


class ParentClass{

}

class ChildClass1 extends ParentClass{

      public function childFunction1(){

      }

}

class ChildClass2 extends ParentClass{

      public function childFunction2(){

      }

}

$myObject = new ParentClass();
$myObject->childFunction1();
$myObject->childFunction2();


But not working. 但不工作。
It's that possible? 这有可能吗?
Is there any alternative solution? 有什么替代解决方案吗?

No, it will not work that way.不,它不会那样工作。 What you're doing is instantiating an empty class and trying to call methods on it.您正在做的是实例化一个空类并尝试对其调用方法。

You should use composition instead.您应该改用组合 The basic idea is to compose multiple objects into your main object.基本思想是将多个对象compose到您的主对象中。 Break off objects by their functionality.按功能划分对象。 Always remember to follow the Single Responsibility Principle and the rest of SOLID.永远记住遵循 单一职责原则和 SOLID 的其余部分。

class ParentClass {

}


class ChildClass1 extends ParentClass{

    public function childFunction1(){

    }

}

class ChildClass2 extends ParentClass{

    public function childFunction2(){

    }

}

$myObject1 = new ChildClass1();
$myObject2 = new ChildClass2();
$myObject1->childFunction1();
$myObject2->childFunction2();

I feel it is like this我觉得是这样的

I've found solution alone.我独自找到了解决方案。

class ParentClass{

      public function childFunctions($className,$functionName){
           $c = ucfirst($className);
           $$className = neew $c();
           return $$className->$finctionName(); // or echo
      }

}

class ChildClass1 extends ParentClass{

      public function childFunction1(){

      }

}

class ChildClass2 extends ParentClass{

      public function childFunction2(){

      }

}
$myObject = new ParentClass();
$myObject->childFunctions("ChildClass1", "childFunction1");
$myObject->childFunctions("ChildClass2", "childFunction2");

That work for my problem.这对我的问题有用。 Maybe someone has the same problem.也许有人有同样的问题。

Thank you anyway.还是很感谢你。

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

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