Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 582
bijiDango Avatar asked Feb 10 '17 00:02

bijiDango


People also ask

What is PHP type hinting?

Type hinting is a concept that provides hints to function for the expected data type of arguments. For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter.

Which data types can be declared with type hinting in PHP?

In simple word, type hinting means providing hints to function to only accept the given data type. In technical word we can say that Type Hinting is method by which we can force function to accept the desired data type. In PHP, we can use type hinting for Object, Array and callable data type.


3 Answers

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.

like image 106
Rendy Eko Prastiyo Avatar answered Oct 19 '22 14:10

Rendy Eko Prastiyo


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

class B
{
    public function foo(mixed $value) {}
}
like image 29
celsowm Avatar answered Oct 19 '22 12:10

celsowm


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.

like image 1
vhu Avatar answered Oct 19 '22 14:10

vhu