当前位置: 动力学知识库 > 问答 > 编程问答 >

Initiate a class by calling a function that returns an instance of that class - PHP?

问题描述:

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?

网友答案:

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

网友答案:

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);
   }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: