开发者

Is is possible to create a factory class in PHP?

Like the BeanFactory in java:

In the much more common case where the BeanFactory itself di开发者_C百科rectly creates the bean by calling its constructor (equivalent to Java code calling new), the class attribute specifies the class of the bean to be constructed. In the less common case where the BeanFactory calls a static, so-called factory method on a class to create the bean, the class attribute specifies the actual class containing the static factory method.

Note:it's not the factory method

$instance = new FactoryClass();

The $instance may be any class instance dynamically


You can use __autoload combined with a static method. This is overly simplified.

MyObject.php:

<?php
class MyObject
{
    public static function Create()
    {
        return new MyObject();
    }

    public function hello()
    {
        print('hello!!!');
    }
}

index.php

<?php
function __autoload($className)
{
    require_once($className . '.php');
}

$o = MyObject::Create();
$o->hello();


It's the worlds crappiest website, but this seems to contain what you want: http://www.devshed.com/c/a/PHP/Design-Patterns-in-PHP-Factory-Method-and-Abstract-Factory/

See the actual website for usage examples, but more or less similar to the java factory.


// define abstract 'ArrayFactory' class
abstract class ArrayFactory{
   abstract public function createArrayObj($type); 
}

// define concrete factory to create numerically-indexed array
objects
class NumericArrayFactory extends ArrayFactory{
   private $context='numeric';
   public function createArrayObj($type){
     $arrayObj=NULL;
     switch($type){
       case "uppercase";
         $arrayObj=new UppercasedNumericArrayObj();
         break;
       case "lowercase";
         $arrayObj=new LowercasedNumericArrayObj();
         break;
       default:
         $arrayObj=new LowercasedNumericArrayObj();
         break; 
     }
     return $arrayObj;
   }
}

// define concrete factory to create associative array objects
class AssociativeArrayFactory extends ArrayFactory{
   private $context='associative';
   public function createArrayObj($type){
     $arrayObj=NULL;
     switch($type){
       case "uppercase";
         $arrayObj=new UppercasedAssociativeArrayObj();
         break;
       case "lowercase";
         $arrayObj=new LowercasedAssociativeArrayObj();
         break;
       default:
         $arrayObj=new LowercasedAssociativeArrayObj();
         break; 
     }
     return $arrayObj;
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜