Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone give me a definition of "type hinting" for Laravel 5 framework

I've read the Laravel documentation and it's still not clear. Since it's vague to me, whenever the term arises in relation to another concept, it's hard to grasp that new concept as well.

like image 957
Spilot Avatar asked Jun 16 '16 16:06

Spilot


People also ask

What is type hinting in laravel?

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.

When was type hinting added PHP?

In May of 2010 support for scalar type hinting was added to the PHP trunk.

What is $this in laravel?

The pseudo-variable $this is available when a method is called from within an object context. $ this is a reference to the calling object.

What is request () in laravel?

Introduction. Laravel's Illuminate\Http\Request class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input, cookies, and files that were submitted with the request.


1 Answers

Type-hinting isn't exclusive to Laravel... Here is a simple explanation.

Example without type hinting:

function foo ($arr = array(), $str = '') {
    var_dump($arr);
    var_dump($str);
}

This function expects an array as the first parameter, and a string as the second. But there is nothing enforcing it. I could call foo() with two strings and there would be no issues.

Example with type hinting:

function foo (array $arr = array(), $str = '') {
    var_dump($arr);
    var_dump($str);
}

The only difference here is the type hint array before $arr. Now trying to call the function with two strings will return a fatal error, because the first argument must be an array.

For further explanation and to find out which type hints are supported, see the documentation.

like image 64
mister martin Avatar answered Oct 06 '22 01:10

mister martin