简体   繁体   中英

How to call a non-static method from another class

This's my second question, even thought, i answered the previous one, on my own. Anyway, I have a basic problem with OOP, on how to call a non-static method from another class. example: We have a class named A in a file A.class.php

class A {

    public function doSomething(){
     //doing something.
    }

}

and a second class named B on another file B.class.php

require_once 'A.class.php';

class B {

    //Call the method doSomething() from  the class A.

}

I think now it's clearn. How to : Call the method doSomething() from the class A ?

Class B will need an object of Class A to call the method on:

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

Alternatively, you can create the instance of A outside of B and pass it into B's constructor to create a global reference to it (or pass it to an individual method, your choice):

class B {
    private $a = null;
    public function __construct($a) {
        $this->a = $a;
    }
    public function doStuff() {
        $this->a->doSomething();
    }
}

$a = new A();
$b = new B($a);

How about injecting class A into B, making B dependant on A. This is the most primitive form of dependency injection:

class A 
{    
  public function doSomething()
  {
    //doing something.
  }
}

class B 
{
  private $a;

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

  //Call the method doSomething() from  the class A.
  public function SomeFunction()
  {
    $this->a->doSomething();
  }  
}

This is constructed like this:

$a = new A();
$b = new B( $a );

You need to instantiate a an object of class A. You can only do this inside a method of class B.

  class B{
     public function doSomethingWithA(){
          $a = new A();
          return $a->doSomething();
      }

  }
class B {

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


}

I know this is an old question but considering I found it today I figured I'd add something to @newfurniturey's answer.

If you wish to retain access to class B within class A this is what I did:

class A 
{    
    private $b = null
    public function __construct()
    {
        $this->b = new B($this);

        if (!is_object($this->b) {
            $this->throwError('No B');
        }

        $this->doSomething();
    }

    public function doSomething() {
        $this->b->doStuff();
    }

    private function throwError($msg = false) {
        if (!$msg) { die('Error'); }
        die($msg);
    }
}

class B {
    public function doStuff() {
        // do stuff
    }
}

This is constructed like this:

$a = new A();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM