开发者

how can we call one class's method through another class's object in php

I want to know that is there any method in PHP by which 开发者_如何学Ci 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


class B extends A {
    // .....
}

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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜