Use 'today' as default value in PHP method

Asked

Viewed 64 times

2

You can do something corresponding to this with PHP (use today’s date as default in the parameter)?

class fiscalOBCharts
{
    private $exercise;

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

2 answers

4


Just as it is not possible to initialize properties of a class expressions or function calls that depend on something with the code already running.

An option would be to already set this date, store in the property and change the method signature leaving the default value 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’t I declare an attribute as an object?

  • I hadn’t even thought of using a builder, solved my problem.

2

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

The default value needs to 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;
    }
}
  • So also employee, more found using a builder more 'beautiful' and clearer for reading.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.