<?php
class Test1 {
function say() {
echo 'hello <br>';
}
}
class Test2 {
function connect() {
$test1 = new Test1();
$test1 -> say();
echo 'connect函数执行 <br>' ;
}
}
$test2 = new Test2();
$test2 -> connect();
?>
通常一个类使用另外一个类的方法就是这么写的。
改成依赖注入的方式。
在实例化Test2的时候,直接将Test1的实例化,传过去。
Test2不再主动实例化Test1类,而且想注入谁都行,不限于Test1类了。
好处:减少了类之间的耦合度。
<?php
class Test1 {
public function say() {
echo 'hello <br>';
}
}
class Test2 {
public $test1;
function __construct($test1) {
$this -> test1 = $test1;
}
function connect() {
$this -> test1 -> say();
echo 'connect函数执行 <br>' ;
}
}
$test1 = new Test1();
$test2 = new Test2($test1);
$test2 -> connect();