Can I set up a default method argument with class property in PHP?

Viewed 7298

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 and 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;
    }
    ...
}
4 Answers

You absolutely can do this. Best of both worlds: initialize your default property AND your method's default argument with a class constant.

class Object {

    const DEFAULT_BLNOVERWRITE = TRUE;

    protected $blnOverwrite = self::DEFAULT_BLNOVERWRITE;

    public function place($path, $overwrite = self::DEFAULT_BLNOVERWRITE) {
        var_dump($overwrite);
    }
}

$Object = new Object();
$Object->place('/'); //bool(true)
Related