bijiDango
bijiDango

Reputation: 1596

Can php have a mixed type hinting?

Say my function want to accept both string and integer. And if it is string, I convert it to int afterwards.

Like

function func(int|string $a) {
    echo is_string($a)?intval($a)+1:$a+1;
}

func(1344);
func('1344');

Upvotes: 12

Views: 12129

Answers (3)

Rendy Eko Prastiyo
Rendy Eko Prastiyo

Reputation: 1098

The feature you asked for is in the proposal phase. See PHP RFC: Union Types.

Update

Mixed type has been ultimately accepted and introduced in PHP 8 released in November 2020.

Upvotes: 16

celsowm
celsowm

Reputation: 394

Mixed was accepted for PHP 8.0: https://wiki.php.net/rfc/mixed_type_v2

class B
{
    public function foo(mixed $value) {}
}

Upvotes: 4

vhu
vhu

Reputation: 12788

Union types RFC has been accepted and implemented for PHP 8.

Mixed type RFC is being voted on, but likely to pass at time of writing this answer.

Upvotes: 1

Related Questions