Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining multiple function argument types in PHP

Tags:

function

php

Is it possible to define a function argument as multiple possible types? For example, a function may take a string or an integer to accomplish something. Is it possible to somehow define it like this?

    function something(int|string $token) {}

Or is only one type per argument supported?

(mind you, I know I can filter input later on, I just like to have my arguments typed)

like image 358
Swader Avatar asked Oct 24 '11 06:10

Swader


People also ask

Can we have multiple arguments in function?

Some functions are designed to return values, while others are designed for other purposes. We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.

How many arguments can a PHP function have?

PHP native functions According to the manual, PHP functions may accept up to 12 arguments.

How many types of arguments are there in functions?

5 Types of Arguments in Python Function Definition: keyword arguments. positional arguments. arbitrary positional arguments. arbitrary keyword arguments.

What are the different types of passing arguments to function?

We use variable-length arguments if we don't know the number of arguments needed for the function in advance. Types of Arbitrary Arguments: arbitrary positional arguments ( *args ) arbitrary keyword arguments ( **kwargs )


2 Answers

2020 Update:

Union types have finally been implemented in PHP 8.0, which is due for release near the end of 2020.

They can be used like this:

class Number {
    private int|float $number;

    public function setNumber(int|float $number): void {
        $this->number = $number;
    }

    public function getNumber(): int|float {
        return $this->number;
    }
}
like image 197
ShaneOH Avatar answered Oct 12 '22 23:10

ShaneOH


No, it is not possible.

Also, type hinting in PHP 5 is now only for classes and arrays. http://php.net/manual/en/language.oop5.typehinting.php

class Foo
{
}

function something(Foo $Object){}
like image 43
Pauly Avatar answered Oct 12 '22 23:10

Pauly