views:

172

answers:

2
class foo(){

   function bar()
   {
     $classInstance = $this->createClassInstance($params);
     $result = $classInstance->getSomething();
   }

   function createClassInstance($params)
   {
     require 'path/to/class.php';
     $myClass = new Class;
     $myClass->acceptParams($params['1']);
     $myClass->acceptMoreParams($params['2']);
     .... lots more params
     return $myClass;
   }

}

Can I initiate a new class by calling a method that returns a class object? The class in question has lots of parameters and I need to call it multiple times within bar() so I thought it would be neater to do it that way, but I can't get it working and want to check if it's possible + good practice?

+2  A: 

That's called factory class (Factory OO Design Pattern).

How it should be done in PHP: http://www.php.net/manual/en/language.oop5.patterns.php

vartec
A: 

What I think you're describing is the Factory pattern, but you're using parameters to set the class variables just like you would in a constructor, so why not just use that?

Edit:

Ah, if you're using the same parameters for the most part then you definitely want the Factory pattern. Just use a static function to return an instance of the class, and put it inside the type of class you're returning:

class MyClass
{
    public static function factory($params)
    {
        $myClass = new MyClass;
        $myClass->acceptParams($params['1']);
        $myClass->acceptMoreParams($params['2']);
        //.... lots more params
        return $myClass;
    }
}

class foo(){

   function bar()
   {
     $classInstance = MyClass::factory(param1, param2);
   }
}
John Rasch
because the class is required 4 times in bar() with about 30 parameters that are all the same apart from 1, 4x30 = lots of duplicate code...
ed209