Scalar Type Hints in PHP

Starting with PHP 7.0, it’s now possible to declare scalar type hints for your method arguments. Previously, we we’re able to use array and callable, but now with PHP 7+, we have access to the following list.

bool

float

int

string

This allows you to build your class methods by explicitly defining the type of data that can be passed through. For instance, if you explicitly define that int’s should be passed within your method, you’d see a TypeError Exception thrown when a string was passed.

Example Usage

Let’s build a calculator capable of summing infinite numbers.

1

2

3

4

5

6

7

8

9

10

<?php

classCalculator

{

publicfunctionsum(float...$numbers)

{

returnarray_sum($numbers);

}

}

Now let’s try and use the above to see how it works.

1

2

3

4

5

6

7

8

9

<?php

$calculator=newCalculator();

try{

echo$calculator->sum(5,10.2);

}catch(TypeError$e){

echo$e->getMessage();

}

The above will output 15.2 as the result. We can pass any number of arguments above.

Here’s another example with a few more arguments.

1

2

3

4

5

6

7

8

9

<?php

$calculator=newCalculator();

try{

echo$calculator->sum(5,10.2,7,9,8);

}catch(TypeError$e){

echo$e->getMessage();

}

This example outputs 39.2 as expected.

Let’s try and break this code now. We’ll try by passing a string to see what happens.

1

2

3

4

5

6

7

8

9

<?php

$calculator=newCalculator();

try{

echo$calculator->sum(5,10.2,'test');

}catch(TypeError$e){

echo$e->getMessage();

}

If you run the above code you’ll see that it is caught by our catch block with the following message:

Argument 3 passed to Calculator::sum() must be of the type float, string given, called in CalculatorExample.php on line 17%

Tags

About This Blog

I'm writing this blog in order to share what I'm learning with the world. Since you learn best by teaching others and writing things down, I figured this would be the best way to really tackle any new technologies I plan on learning. I hope this blog will help you as much as it will benefit me.