Skip to content
Advertisement

PHP Union Types with default value

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

Advertisement

Answer

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;
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement