Richard Quadling wrote:
Hi. I have a scenario where I would _like_ to have multiple constructors for a class. Each constructor has a greater number of parameters than the previous one. e.g. <?php class myClass { __construct(string $Key) // use key to get the complex details. __construct(string $Part1, string $Part2, string $Part3) // Alternative route to the complex details. __construct(array $Complex) // All the details } Essentially, SimpleKey is a key to a set of predefined rules. Part1, 2 and 3 are the main details and well documented defaults for the rest of the rules. Complex is all the rules. Each constructor will end up with all the parts being known ($Key, $Part1, $Part2, $Part3, $Complex). But, PHP doesn't support multiple constructors. Initially I thought about this ... __construct($Key_Part1_Complex, $Part2=Null, $Part3=Null) But then documenting the first param as being 1 of three different meanings is pretty much a no go. So I'm looking for a clean and easily understood way to provide this. I won't be the only user of the code and not everyone has the same knowledge level, hence a mechanism that is easily documentable. I think I may need a factory with multiple methods (FactoryKey, FactoryPart1To3, FactoryComplex). Make the factory a static/singleton. All these methods eventually call the real class with the complex rule. Is that obvious enough?
Factory method is probably the cleanest and simplest solution. Just pass an ID as the first parameter to the real constructor and then it can route to the appropriate behaviour:
<?php $factory->getInstanceBleh(); class Foo { const SUPER_SPECIAL_BLEH = 1; const SUPER_SPECIAL_BLAH = 2; const SUPER_SPECIAL_BLUH = 3; function __construct( $superSpecialId, ... ) { switch( $superSpecialId ) { } } function getInstanceBleh() { return new Foo( Foo::SUPER_SPECIAL_1 ); } } ?> Cheers, Rob. -- http://www.interjinn.com Application and Templating Framework for PHP -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php