PHP Passing an instance of a class to another class

心已入冬 提交于 2019-12-01 16:06:56

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);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!