brown2005 Posted February 7, 2013 Share Posted February 7, 2013 class Function1 { function a() { } function c () { $this->a() } } class Function2 { funcation b () { Function1->a(); } } is it possible to get rid of function c and just use b calling in function a? Quote Link to comment https://forums.phpfreaks.com/topic/274183-calling-a-class-function-in-a-class-function/ Share on other sites More sharing options...
Hall of Famer Posted February 7, 2013 Share Posted February 7, 2013 (edited) Yeah its possible, but the way you are using classes is somewhat weird. I dont think you grasp the concept of OOP nicely. Heres what you are supposed to do in class 2: class Class1{ public function a(); public function c(){ $this->a(); } } class Class2{ public function b(){ $class1 = new Class1(); $class1->a(); } } Or you can declare all methods to be static so you do not need to instantiate an object. It seems to me that you have no idea what a class does and how class methods(member functions) differ from procedural functions. Edited February 7, 2013 by Hall of Famer Quote Link to comment https://forums.phpfreaks.com/topic/274183-calling-a-class-function-in-a-class-function/#findComment-1410874 Share on other sites More sharing options...
Christian F. Posted February 8, 2013 Share Posted February 8, 2013 Better to use dependency injection, and avoid the interdependence between classes: class Class1 { public function a() { // Do something. return 'test'; } class Class2 { private $data; public function __construct (Class1 $dataStore) { $this->data = $dataStore; } public function b(){ return $this->data->a(); } } // Create the objects $objectA = new Class1 (); $objectB = new Class2 ($obejctA); // Print out the results from Class1::a() via the second class. echo $objectB->b (); You'll also note that I've removed the c () method, as it wasn't doing anything, and added a body to the a () method. Quote Link to comment https://forums.phpfreaks.com/topic/274183-calling-a-class-function-in-a-class-function/#findComment-1410890 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.