Complete example of php object factory class

  • 2021-11-01 02:22:32
  • OfStack

This article illustrates the php object factory class. Share it for your reference, as follows:


<?php
/**
 *  Object factory 
 * @author flynetcn
 */
class ObjectFactory
{
  private static $objSet = array();
  /**
   *  Empty the objects in the factory 
   */
  public function clear()
  {
    self::$objSet = array();
  }
  /**
   *  Create an object in the factory and return it 
   *  Parameter format: $class_name, $class_param1, $class_param2, ...
   */
  public static function create()
  {
    $argc = func_num_args();
    if ($argc <= 0) {
      throw new Exception('params error', 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;
  }
}

More readers interested in PHP can check the topics on this site: "Introduction to php Object-Oriented Programming", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of PHP Network Programming Skills", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: