Jump to content

calling a class function in a class function


brown2005

Recommended Posts

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.