龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

php工厂模式

时间:2014-07-22 14:50来源: 作者: 点击:
分享到:
php生成工厂模式就是生成对象!
php生成工厂模式就是生成对象!
 class FruitFactory {
        private $history, $class, $constructor_args;
        
        /**
         * Create a factory of given class. Accepts extra arguments to be passed to
         * class constructor.
         */
        function __construct( $class ) {
            var_dump($args = func_get_args());
			
            $this->class = $class;//类名
            $this->constructor_args = array_slice( $args, 1 );//参数
        }
        
        function __call( $method, $args ) {
		
            $this->history[] = array(
                'action'    => 'call',
                'method'    => $method,
                'args'   	=> $args
            );
			var_dump($this->history);
        }
        
        function __set( $property, $value ) {
            $this->history[] = array(
                'action'    => 'set',
                'property'    => $property,
                'value'        => $value
            );
			var_dump($this->history);
        }
        
        /**
         * Creates an instance and performs all operations that were done on this MagicFactory
         */
        function instance() {
            # use Reflection to create a new instance, using the $args 
            $reflection_object = new ReflectionClass( $this->class );
            $object = $reflection_object->newInstanceArgs( $this->constructor_args ); 
			
         
            foreach( $this->history as $item ) {
                if( $item['action'] == 'call' ) {  
				//运行实例的方法
                    call_user_func_array( array( $object, $item['method'] ), $item['args'] );
                }//属性赋值
                if( $item['action'] == 'set' ) {
                    $object->{$item['property']} = $item['value'];
                }
            }
            
            # Done
            return $object;
        }
    }
    
    class Fruit {
        private $name, $color;
        public $price;
        
        function __construct( $name, $color ) {
            $this->name = $name;
            $this->color = $color;
        }
        
        function setName( $name ) {
            $this->name = $name;
        }
        
        function introduce() {
            print "Hello, this is an {$this->name} {$this->color}, its price is {$this->price} RMB.";
        }
    }
    
    # Setup a factory
    $fruit_factory = new FruitFactory('Fruit', 'Apple', 'Gonn');
    $fruit_factory->setName('Apple');
    $fruit_factory->price = 2;
    
    # Get an instance
    $apple = $fruit_factory->instance();
    $apple->introduce();

链接地址http://www.nowamagic.net/librarys/veda/detail/377
精彩图集

赞助商链接