PHP Passing an instance of a class to another clas

2019-02-22 01:54发布

问题:

I'm still kind of new to PHP OO programming techniques and I have a very simple broad question, is it generally bad practice to instantiate a class in a class then pass that instance to another class?

What I want is to be able to create an instance of a specific class I know I will always need through each user request. Class two is more than anything just a helper class, ideally in my application it would be a "loader" that loads the views.

First class which calls the other two classes:

require 'classTwo.php';
require 'classThree.php';

class first {
     public $classTwo, $classThree;

     public function __construct() {
          $this -> classTwo = new classTwo;
          $this -> classThree = new classThree;

          $this -> classThree -> displayNum( $this -> classTwo );

     }
}

Second class which is the helper class:

class classTwo {
     public function returnVal() {
          return 123;
     }
}

Third class is the action class where actual work and final display would happen:

class classThree {
     public function displayNum( $instance ) {
          echo $instance -> returnVal();
     }
}

Overall I just want to know if this is bad practice because I never seen it done before.

Thanks in advance!

回答1:

It is good practice to inject any dependent objects, as this allows you to mock quite easily during unit testing.

Generally speaking, if you have ClassA and it relies on an instance of ClassB to function then you could do something like..

$objectB = new ClassB();
$objectA = new ClassA($objectB);

Take a look at http://net.tutsplus.com/tutorials/php/dependency-injection-in-php/

EDIT: Constructor injection is passing the dependency into the new object's constructor (as demonstrated above).

Setter injection is using a method to set the dependency, and is usually utilised when the dependency isn't critical:

$objectB = new ClassB();
$objectA = new ClassA();
$objectA->setObjectB($objectB);


回答2:

Yes. This would make it a pain to unit test your first class because there are dependencies hard coded in it.

Either inject the instances of the classes or inject a factory.