概念
    高层模块不该依赖底层模块,二者都该依赖其抽象(接口、抽象类);抽象不该依赖其细节;细节依赖抽象;

    代码实现

    1. <?php
    2. interface Str
    3. {
    4. public function randStr();
    5. }
    6. class Letter implements Str
    7. {
    8. public function randStr()
    9. {
    10. $arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
    11. $indexs = array_rand($arr, 4);
    12. $str = '';
    13. foreach ($indexs as $index) {
    14. $str .= $arr[$index];
    15. }
    16. return $str;
    17. }
    18. }
    19. class Num implements Str
    20. {
    21. public function randStr()
    22. {
    23. return mt_rand(1000, 9999);
    24. }
    25. }
    26. class C
    27. {
    28. public function boot(Str $str)
    29. {
    30. echo "生成字符串预计需要3秒..." . PHP_EOL;
    31. for ($i = 3; $i > 0; $i--) {
    32. sleep(1);
    33. echo "{$i}秒" . PHP_EOL;
    34. }
    35. echo $str->randStr() . PHP_EOL;
    36. }
    37. }
    38. $letter = new Letter();
    39. $num = new Num();
    40. $c = new C();
    41. $c->boot($letter);
    42. $c->boot($num);