2 simmilar classes - how make parent

liunx

Guest
i have two classes
class student{
private $information;
static function create()
{
//getting data from data_base
return new student;
}
}

and

class teacher{
private $information;
static function create()
{
//getting data from data_base
return new teacher;
}
}

they're very simmilar so I try to make parent class for there
class person
{
protected $information;
//getting data from data_base
static function create()
{
//getting data from data_base
SOMETHING;
}
}

but I don't know what I should write in place - SOMETHING, because it should depends on class. if I use student::create() in place SOMETHING should be return new student, and if I use teacher::create() in place SOMETHING should be return new teacher. Please help me.

--------------
sorry for mistakes, my English isn't goodYou have encountered one of PHPs more annoying limitations. The person::create method does not know that it was called using student::create.

One solution is to add a create method to each of the derived classes and then pass a parameter to the parent.

class student extends person
{

static function create()
{
parent::create('student');
}

This can get old real fast especially if you have more than one static function that needs to be mapped.

The only real solution is to use a factory object to create your stuff. maybe something like:

class PersonFactory
{
$itemClassName = NULL;

function create()
{
return new $this->$itemClassName();
}
}
class StudentFactory extends PersonFactory
{
$itemClassName = 'Student';
}
$studentFactory = new StudentFactory();
$student = $studentFactory->create();

$factory = new PersonFactory();
$student = $factory->createStudent();

May seem like a bit of a pain but, in general, using objects is easier than using statics.If teacher/student extends parent, than anything in your create logic should be generic--anything that is teacher- or student-specific belongs in the teacher and student class respectively. (IMHO) If you place subclass-specific login in a base/abstract class... it no longer serves as a generic base for other, possibly new, classes--it's just serving to put your class-specific logic in more than one place.
 
Back
Top