سؤال

I am implementing Factory Pattern in php. There is an AbstractFactory Class and one is ConcreteFactory class. Following is code which i am using :

/** AbstractFactory.php */
abstract class AbstractFactory{
      abstract function xyz();
}


/** ConcreteFactory.php */
require_once "AbstractFactory.php"
require_once "ABC.php"
class ConcreteFactory extends AbstractFactory{
     public function xyz(
           return new ABC();   
     );   
}


/** Client.php */

require_once "ConcreteFactory .php"
class Client extends ConcreteFactory {
   public function dothis() {

       // Now i want to create AbstractFactory type object from ConcreateClass

       AbstractFactory $afobject = new ConcreteFactory();
    }
}

(AbstractFactory $afobject ) returns a parse error.
Can anyone please tell me how to create this object?

هل كانت مفيدة؟

المحلول

you create it like this:

$afobject = new ConcreteFactory();

There are no real types in PHP, so down-casting is not needed. Just use the object as if it was the abstract factory. Usually you indicate that in the documentation. So let's say you want to pass that object to a method that only accepts abstract factories, then just indicate it in the @param attribute of your documentation. I would not recommend to use Type-Hints for this purpose, as it will raise a notice if you try to put in the concrete class. If you want to make sure you got an abstract factory, check it with instanceof in the first lines of your method.

Hope this helps, Thomas

نصائح أخرى

PHP is not Java. You cannot declare the instance like this:

AbstractFactory $afobject = new ConcreteFactory();

You just do

$afobject = new ConcreteFactory();

and that will give you a ConcreteFactory instance in $afobject.

There is other syntax errors as well:

 public function xyz(
       return new ABC();   
 );   

should read

 public function xyz() {
       return new ABC();   
 }   

and you are missing a semicolon after

require_once "ConcreteFactory .php"

Try to code with an IDE that does syntax highlighting or run your code with php -l filename from the command line to lint it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top