What is a Factory Design Pattern in PHP?

后端 未结 9 1033
清歌不尽
清歌不尽 2020-11-27 10:15

This confuses me, in the most simplest terms what does it do? Pretend you are explaining to your mother or someone almost please.

9条回答
  •  时光说笑
    2020-11-27 10:56

    The classic approach to instantiate an object is:

    $Object=new ClassName();
    

    PHP has the ability to dynamically create an object from variable name using the following syntax:

    $Object=new $classname;
    

    where variable $classname contains the name of class one wants to instantiate.

    So classic object factoring would look like:

    function getInstance($classname)
    {
      if($classname==='Customer')
      {
        $Object=new Customer();
      }
      elseif($classname==='Product')
      {
        $Object=new Product();
      }
      return $Object;
    }
    

    and if you call getInstance('Product') function this factory will create and return Product object. Otherwise if you call getInstance('Customer') function this factory will create and return Customer type object (created from Customer() class).

    There's no need for that any more, one can send 'Product' or 'Customer' (exact names of existing classes) as a value of variable for dynamic instantiation:

    $classname='Product';
    $Object1=new $classname; //this will instantiate new Product()
    
    $classname='Customer';
    $Object2=new $classname; //this will instantiate new Customer()
    

提交回复
热议问题