tags:

views:

40

answers:

4

I'm using php 5.2.6. I want to have a default value for an argument in a method, but it seems I'm getting a bit too clever.

The class property `blnOverwrite' is defaulted an settable elsewhere in the class. I have a method where I want to have it settable again, but not override the existing value. I get an error when I try this:

public function place( $path, $overwrite = $this->blnOverwrite ) { ... }

Must I do something like this?

public function place( $path, $overwrite = NULL ) { 
    if ( ! is_null($overwrite) ) {
        $this->blnOverwrite = $overwrite;
    }
    ...
}
+2  A: 

Yes, you have to do it this way. You cannot use a member value for the default argument value.

From the PHP manual on Function arguments: (emphasis mine)

A function may define C++-style default values for scalar arguments. […] PHP also allows the use of arrays and the special type NULL as default values. […] The default value must be a constant expression, not (for example) a variable, a class member or a function call. […] Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

Gordon
A: 

you just can shorten it a little:

public function place( $path, $overwrite = NULL ) { 
    if(!is_null($overwrite))$this->blnOverwrite = $overwrite;
    ...
}

but thats nearly the same

revaxarts
A: 

PHP doesn't have support to do it < http://php.net/manual/en/functions.arguments.php >, may you can use < http://www.php.net/manual/en/function.func-get-args.php >... but I don't think a great idea.

Felipe Cardoso Martins
+1  A: 

You must do it that way, afaik, or use a class constant since php 5.3 but of course its fixed and cant be changed later so i would definitely go with your own solution:

class foo{
    const constant = 'bar';

    public function place($path, $overwrite = self::constant ) { 
        die('bla' . $overwrite);
    }
}

$bar = new foo();
$bar->place('baz');
Hannes