A community in which webmasters can ask for help with topics such as PHP coding , MySQL , IT jobs, web design, IT security.
Current location:homephp forumphp talk in 2009 yearInitiate a class by calling a function that returns an instance of that class - PHP? - page 1
User InfoPosts
Initiate a class by calling a function that returns an instance of that class - PHP?#1
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?

posted date: 2009-04-07 11:48:00


Re: Initiate a class by calling a function that returns an instance of that class - PHP?#2
I had made out the solution of this problem. click to view my topic...

hope that hepls.

posted date: 2009-04-07 11:48:01


Re: Initiate a class by calling a function that returns an instance of that class - PHP?#3
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

posted date: 2009-04-07 11:50:00


Re: Initiate a class by calling a function that returns an instance of that class - PHP?#4
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); }}

posted date: 2009-04-07 11:51:00


Re: Initiate a class by calling a function that returns an instance of that class - PHP?#5
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...

posted date: 2009-04-07 11:54:00


select page: « 1 »
Copyright ©2008-2017 www.momige.com, all rights reserved.