declare types to function arguments, return values, and properties

How to declare types to function arguments, return values, and properties?

Want to make a function accept only the given data type? Yes, it is possible with the help of PHP type hinting.

PHP type hinting allows you to declare the data types to a function. After declaring the type of data the function can accept only that type of data.

PHP Type hinting example

Type declaration for function arguments

function funcName(type $varName, type $varName2){}

Here is the list of data-type that you can declare.

Example:

<?php
function sayHi(string $name, int $age){
    echo "Hi My name is $name and I'm $age years old.";
}

sayHi("Joe", 22);
Hi My name is Joe and I'm 22 years old.

You can declare type to the return value

function funcName() : type {}

The following add() function must return a string value.

<?php
function add(int $a, int $b) : string{
    $sum = $a + $b;
    return "Sum is - $sum";
}

echo add(5, 4);
Sum is - 9

Declare types in properties and methods of a class

Learn – PHP Class and Objects.

<?php
class MyClass{
    // Type declaration in a Property
    public int $value;

    function __construct(int $a){
        $this->value = $a;
    }
}

$obj = new MyClass(14);

You can declare a class as a type

The $a parameter of the test() function must be an object of the MyClass.

<?php
class MyClass{
    function add(int $a, int $b) : int{
        return $a + $b;
    }
}

function test(MyClass $a){
    echo $a->add(2, 5);
}

$obj = new MyClass();

test($obj);
7