php object factory class

WBOY
Release: 2016-07-30 13:30:57
Original
982 people have browsed it
<?php
/**
 * 对象工厂
 * @author flynetcn
 */
class ObjectFactory
{
	private static $objSet = array();

	/**
	 * 清空工厂中的对象
	 */
	public function clear()
	{
		self::$objSet = array();
	}

	/**
	 * 在工厂中创建对象并将其返回
	 * 参数格式:$class_name, $class_param1, $class_param2, ...
	 */
	public static function create()
	{
		$argc = func_num_args();
		if ($argc <= 0) {
			throw new Exception(&#39;params error&#39;, 1);
		}
		$args = func_get_args();
		$class_name = array_shift($args);
		$params = $args;
		if (!$params) {
			$class_sign = $class_name;
		} else {
			$param_sign = serialize($params);
			if (strlen($param_sign) > 100) {
				$param_sign = md5($param_sign);
			}
			$class_sign = $class_name.'@'.$param_sign;
		}
		if (isset(self::$objSet[$class_sign])) {
			return self::$objSet[$class_sign];
		}
		$ref = new ReflectionClass($class_name);
		if ($ref->hasMethod('__construct') && !empty($params)) {
			$obj = $ref->newInstanceArgs($params);
		} else {
			$obj = $ref->newInstance();  
		}
		self::$objSet[$class_sign] = $obj;
		return $obj;
	}
}
Copy after login

Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces the PHP object factory class, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!