views:

597

answers:

3

I have a class in PHP like so:

class ParentClass {
    function __construct($arg) {
        // Initialize a/some variable(s) based on $arg
    }
}

It has a child class, as such:

class ChildClass extends ParentClass {
    function __construct($arg) {
        // Let the parent handle construction. 
        parent::__construct($arg); 
    }
}

What if, for some reason, the ParentClass needs to change to take more than one optional argument, which I would like my Child class to provide "just in case"? Unless I re-code the ChildClass, it will only ever take the one argument to the constructor, and will only ever pass that one argument.

Is this so rare or such a bad practice that the usual case is that a ChildClass wouldn't need to be inheriting from a ParentClass that takes different arguments?

Essentially, I've seen in Python where you can pass a potentially unknown number of arguments to a function via somefunction(*args) where 'args' is an array/iterable of some kind. Does something like this exist in PHP? Or should I refactor these classes before proceeding?

A: 

Yeah, it's pretty bad practice to make a child class that uses different constructor arguments from the parent. Especially in a language like PHP where it's poorly supported.

Of course, the generic way to pass a set of "whatever arguments we might ever want" in PHP is to pass a single argument consisting of an array of configuration values.

chaos
Of course, there you have the "Magic Container" code smell (http://c2.com/cgi/wiki?MagicContainer). What you need is a Parameter Object (http://c2.com/cgi/wiki?ParameterObject).
Ewan Todd
The magic container is unfortunately widely used in php applications, nonetheless.
soulmerge
+3  A: 

There is something like this in php, though a bit verbose:

$args = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $args);
soulmerge
+1  A: 

Check out these functions on php.net:

func_get_args
func_num_args

Also, if you want to make an optional argument, you can do this:

class ParentClass {
    function __construct($arg, $arg2="Default Value") {
        // Initialize a/some variable(s) based on $arg
    }
}
David Barnes