tags:

views:

163

answers:

4

I want to know that is there any method in PHP by which i can call one class's method from another class object. let me clear here is one class

    class A() {
    public function showData(){
        //here is method of class A
   }
}

 // here is another class

class B(){
      public function getData(){
            //some method in class B
         }
}

  //now i create two objects

$objA= new class A();
$objB=new class B();

now i want to call this
$objB->showData();<---

is that possible .. by any how method( using public, inheritence,child parent etc...) please help me

+2  A: 
class B extends A {
    // .....
}

now you can instantiate an object of class B and call methods from class A too.

kemp
no other solution?? can't we use global object of class A in class B method
hello
What's wrong with this solution?
kemp
+1  A: 

In the way your question is presented, @kemp's answer makes a lot of sense. Now, you could also:

Instantiate A within B

class A {
    public function showData() {
        // some logic here
    }
}

class B {
    public function getData(){
        $a = new A;
        $a->showData();
    }
}

$b = new B;
$b->getData();

Inject A into B

class A {
    public function showData() {
        // some logic here
    }
}

class B {
    public function getData(A $a){
        $a->showData();
    }
}

$b = new B;
$b->getData(new A);

What's best depends on the functionality you want to implement.

nuqqsa
A: 

You could also use magic methods

Class A {
    public function showData() {}
}

Class B {
    protected $a = null;
    public function __construct(A $a) {
        $this->a = $a;
    }
    public function __call($name, $args) {
        if (is_callable(array($this->a, $name))) {
            return $this->a->$name();
        }
        throw new BadMethodCallException('Invalid Method');
    }
    public function getData() {}
}

So that way, when you call $b->showData(), __call('showData', array()) will be called on B. B will then check to see if it can call $a->showData(), and if it can, it will.

ircmaxell
+1  A: 

my two pence;

class A {
    public function showData() {
        // some logic here
    }
}

class B {

    private $a;

    function __construct(){
        $this->a = new A();
    }

    public function A(){
        return $this->a;
    }

    public function getData(){
       //whatever
    }
}

$bah = new B();

$bah->A()->showData();

I believe this to be data hiding/encapsulation under OO concepts.

Damon Skelhorn