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.

Edited by Hall of Famer
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.