Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

default

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;
    }
    ...
}
like image 405
user151841 Avatar asked Sep 29 '10 15:09

user151841


People also ask

What is PHP default argument?

PHP allows you to use a scalar value, an array, and null as the default arguments.

Can we give default value to arguments?

In C++ programming, we can provide default values for function parameters. If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.

In which situation default arguments are useful?

D. Default arguments are useful in situations where some arguments always have the same value.


2 Answers

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.

like image 147
Gordon Avatar answered Sep 19 '22 14:09

Gordon


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)
like image 24
user1271684 Avatar answered Sep 19 '22 14:09

user1271684