Norbert Wenzel wrote:
Hi,
I'm using PHP5 and try to do something like this:
I have a base class called 'Entry' and a child class called
'ExtendedEntry'. I want to read all Entries to a certain topic from a
database.
While constructing the EntryObject I would like to look if Entry is a
simple Entry or an ExtendedEntry. I want the new object to be an
ExtendedEntry - if possible - and otherwise to be an Entry.
It was not possible to return the object in the __construct() function
and it was not possible to reassign $this with code like
$this = new ExtendedEntry()
also in the __construct() function. And I tried to always generate an
ExtendedEntry with a flag, that says it is really Extended and a
typecast afterwards, but I wasn't able to typecast to another object by
(Entry) $extEntry.
Any suggestions how to solve this problem without writing a
generateEntry() function, that looks into the database and then calls
the correct class type?
no not really - although I would suggest to create a static member function
(method) in the base class that acts as the factory e.g:
class Entry
{
static public function create($key = array(), $type = null)
{
// $type could be used to force the type of class
// or specify a class for a new object (as opposed to
// an object created from existing database content
// $key could be used to pass the relevant primary key(s)
// in order to retrieve the relevant data. (leave empty to create
// a 'new' object?)
}
}
actually you might try looking into the delegation pattern which could offer an alternative
to a factory function (i.e. the object can make extra methods from contained/helper
classes available depending on the type of data retrieved)
thanks in advance,
Norbert
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php