Use 'today' as default value in PHP method

2

Is it possible to do something matching this with PHP (use today's date as the default in the parameter)?

class fiscalOBCharts
{
    private $exercise;

    public function exercise(string $exercise = date('d/m/Y')){
        $this->exercise = $exercise;        
        return $this;
    }
}

PS: The above code does not work.

    
asked by anonymous 30.08.2017 / 19:37

2 answers

3

Just like you can not initialize properties of a class expressions or calls of functions that depend on something with the code already running.

An option would already be to set this date, store in the property and change the signature of the method leaving the default value as null / empty.

class fiscalOBCharts
{
    private $exercise;

    public function __construct(){
        $this->exercise = date('d/m/Y');
    }

    public function exercise(string $exercise=null){
        if(!empty($exercise)) $this->exercise = $exercise;
        return $this;
    }
}

Related:

Why can not I declare an attribute as an object?

    
30.08.2017 / 19:49
2

As you can see in the documentation, in the topic Function Arguments :

  

The default value must be a constant expression, not (for example)   a variable, a class member, or a function call.

For your case, you can do:

class fiscalOBCharts
{
    private $exercise;

    public function exercise(string $exercise = ""){

        $this->exercise = ($exercise) ?: date('d/m/Y');        
        return $this;
    }
}
    
30.08.2017 / 19:53