tanim tanim - 29 days ago 10
PHP Question

How can I call another class method into another class method in PHP

I'm trying to get the method using

call_user_func
in PHP but the fact is I can't get it in proper way. My data is stored into another class method and I would like to fetch that data into another class method. First of all I've create an object with some param which are given in other class. Based on the param the class starts it's work than store the data into the method. My problem is I've already called an object after class now how can I call that object again into another class. Maybe you can understand it by the sample code:

class A{
public $a;
public $b;
public function __construct(){

}
public function x(){
$this->a = "something";
$this->b = "something1";
}
public function abc(){
$printthis = call_user_func(array($obj2,$method_name);
echo $printthis;
}
}
$obj1 = new A;
$obj1->x;

class B{
public $a;
public $b;
public function __construct($c,$d){
$this->a = $c;
$this->b = $d;
}
public function abc(){
//some code here that returns something
}
public function abd(){
//some code here that returns something
}
}
$obj2 = new B($obj1->a, $obj1->b);


In the above code section I don't know how to get that data from B class into A class. Can anyone help me in this topic? I'm getting nothing from here. A code example can explain everything.

Answer

Basic inheritance will resolve all your issues.

class A{
    public $a;
    public $b;
    public function __construct(){

    }
    public function x(){
      $this->a = "something";
      $this->b = "something1";
   }
   public function abc(){
    $printthis = call_user_func(array($obj2,$method_name);
    echo $printthis;
   }

   // to call abd() method from class B inside this class
   function call_child_method(){
    if(method_exists($this, 'abd')){
        $this->abd();
    }
}
}
$obj1 = new A;
$obj1->x();

class B extends A{  // object will can call both methods of class A and B
   public $a;
   public $b;
   public function __construct($c,$d){
      $this->a = $c;
      $this->b = $d;
   }
   public function abc(){
      //some code here that returns something
   }
   public function abd(){
     //some code here that returns something
   }

   // to call X() method from class A inside this class
   parent::X(); 
 }
 $obj2 = new B($obj1->a, $obj1->b);