简体   繁体   中英

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. Break off objects by their functionality. Always remember to follow the Single Responsibility Principle and the rest of 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.

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