• php设计模式-简单依赖注入容器


    <?php
    class A 
    {
        private $_b;
    
        public function __construct($b)
        {
            $this->_b = $b;
        }
    
        public function sayHello()
        {
            $this->_b->sayHello();
            echo 'I am A<br>';
        }
    }
    
    class B
    {
        private $_c;
    
        public function __construct($c)
        {
            $this->_c = $c;
        }
    
        public function sayHello()
        {
            $this->_c->sayHello();
            echo 'I am B<br>';
        }
    }
    
    class C
    {
        public function sayHello()
        {
            echo 'I am C<br>';
        }
    }
    
    // 依赖注入容器
    class DIContainer
    {
        private $_container;
    
        public function __set($key, $val)
        {
            $this->_container[$key] = $val;
        }
    
        public function __get($key)
        {
            return $this->_container[$key]($this);
        }
    }
    
    $container = new DIContainer();
    $container->c = function(){
        return new C;
    };
    
    $container->b = function($container){
        return new B($container->c);
    };
    
    $container->a = function($container){
        return new A($container->b);
    };
    
    $container->a->sayHello();
    

      输出结果:

    I am C
    I am B
    I am A
    

      

  • 相关阅读:
    sw
    ++1
    test
    为了
    发送邮件
    新建121212
    29012
    pthread_create/join函数
    recv函数学习
    socketpair用法学习
  • 原文地址:https://www.cnblogs.com/xiangdongsheng/p/13357964.html
Copyright © 2020-2023  润新知