0
class BetterDOMDocument extends DOMDocument 
{
    function __construct($version = null, $encoding = null) {
        parent::__construct($version, $encoding);
    }
}

This code will generate an XML header with an empty version attribute.

However, I cannot just define the constructor as:

function __construct($version, $encoding) {}

Because now PHP complains about Undefined Variable usage if I want to use this constructor without passing any arguments.

DOMDocument does not require be to passed $version, it'll use a default if I don't pass a value. How can I override the constructor while keeping the argument handling of the base class unchanged, without duplicating the specific default values?

I'm interested in this not in terms of a problem I'm stuck at that needs a workaround, but in terms of PHP language design. Can one , and how so, reproduce the behavior of DOMDocument in PHP, or is there something special about how internal code is able to deal with undefined values?

miracle2k
  • 29,597
  • 21
  • 65
  • 64

1 Answers1

3

Just set some sensible defaults:

class BetterDOMDocument extends DOMDocument 
{
    function __construct($version = '1.0', $encoding = 'UTF-8') {
        parent::__construct($version, $encoding);
    }
}

If this is actually all you're doing in the constructor, you don't need to overload it in the first place unless the purpose is set your own defaults.

In PHP, and I suspect in other languages, you actually can't tell a function to "use default" unless passing NULL as an argument (for instance) is handled by the class in such a way that it will use a default value instead. You'll have to work with tte design of the existing class/function, which may vary.

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
  • Actually, ``DOMDocument`` does not require be to passed ``$version`` it'll use a default if I don't pass a value. The question is how I can reproduce the behavior without duplicating the actual default. I've updated the question to make this clearer. – miracle2k Mar 14 '12 at 09:53
  • Regarding your edit: My mistake, I read the [docs](http://www.php.net/manual/en/domdocument.construct.php) incorrectly. You actually can't tell a function to "use default" unless passing NULL as an argument (for instance) is handled by the class in such a way that it will use a default value instead. For example: http://stackoverflow.com/questions/9541776/php-function-ignore-some-default-parameters/9541834 – Wesley Murch Mar 14 '12 at 09:59
  • Also see: http://www.php.net/manual/en/functions.arguments.php There *may* be workarounds with stuff like `func_get_args()` for *some* instances, but it really should be dealt with on a case-by-case basis. The literal thing you're asking cannot be done. – Wesley Murch Mar 14 '12 at 10:07