Home > OS >  PHP Union Types with default value
PHP Union Types with default value

Time:11-10

I wanted to implement methods with union-type dependencies for the argument like so:

public function example(string|array $value = false){
    $data  = $value? $value : $this->otherValue;
}

but it's triggering an error

 Cannot use bool as the default value for parameter $value of type array|string.

I looked through the documentation but there is no mention of this. Thanks in advance

CodePudding user response:

You can add new type for other type hint:

<?php

class a{
    public function example(string|array|bool $value = false){
        $data  = $value? $value : $this->otherValue;
    }
}
  • Related