Factory Method return you the specific object by params he gets.
Lets make an example… we got 2 different classes for students that extends StudentAbstract class,
now we can make factory class that return the class by param.
StudentAbstract.php
1 2 3 4 | abstract class StudentAbstract { abstract function getFirstName(); abstract function getLastName(); } |
FirstGradeStudent.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | include_once('StudentAbstract.php'); class FirstGradeStudent extends StudentAbstract { private $firstName; private $lastName; private function __construct() { $this->firstName = "Garry"; $this->lastName = "Lachman"; } public function getFirstName() { return $this->firstName; } public function getLastName() { return $this->lastName; } } |
SecondGradeStudent.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | include_once('StudentAbstract.php'); class SecondGradeStudent extends StudentAbstract { private $firstName; private $lastName; private function __construct() { $this->firstName = "Polani"; $this->lastName = "Almoni"; } public function getFirstName() { return $this->firstName; } public function getLastName() { return $this->lastName; } } |
GetStudentFactory.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | include_once("FirstGradeStudent.php"); include_once("SecondGradeStudent.php"); class GetStudentFactory { public function getStudent($grade) { $student = NULL; switch ($grade) { case "first": $student = new FirstGradeStudent(); break; case "second"; $student = new SecondGradeStudent(); break; default: $student = new FirstGradeStudent(); break; } return $student; } } |
Test.php
1 2 3 4 5 6 7 8 9 | include_once("GetStudentFactory.php"); $factory = new GetStudentFactory(); $firstGrade = $factory->getStudent("first"); // return FirstGradeStudent class $secondGrade = $factory->getStudent("second"); // return SecondGradeStudent class |
Have Fun ![]()
Garry Lachman

CodeIgniter – PHP 5 MVC Framework
I really never used frameworks, i always build my system without any frameworks.
but no more… after few days with CodeIgniter i`m in Love…
“CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. If you’re a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if you’re tired of ponderously large and thoroughly undocumented frameworks”
Have a nice day
Garry Lachman