Type Hinting in PHP

Share this article

Since PHP 5 you can use type hinting to specify the expected data type of an argument in a function declaration. When you call the function, PHP will check whether or not the arguments are of the specified type. If not, the run-time will raise an error and execution will be halted. Valid types are class names for arguments that receive objects and array for those that receive arrays. Here’s an example:

<?php
function enroll(Student $student, School $school) {
echo "Enrolling " . $student->name . " in " . $school->name;
}
By telling PHP exactly what kind of objects the enroll() method expects to receive, you can ensure that students are being enrolled in a school instead of a nunnery or a 401K. Likewise, you know that you won’t have any stubborn pachyderms showing up for the first day of third grade. What would happen if I tried to enroll myself into medicare?
<?php
$me = new Student("Amanda");
$medicare = new Program("Medicare");
$enroll = enroll($me, $medicare);
Although I am a student, the following error would occur:
Catchable fatal error: Argument 2 passed to enroll() must be an instance of School, instance of Program given, called in typehint.php on line 32 and defined in typehint.php on line 6
If null is used as a default value for an argument it will also be allowed. Here’s an example, this time with arrays:
<?php
function startParty(array $guests, array $food = null) {
    // party stuff...
}
$guests = array("Susan Foreman", "Sarah Jane Smith", "Rose Tyler", "Donna Noble");
startParty($guests, null);
There’ll be a party as long as there are guests, with or without food.

Limitations of Hinting

Any defined class can be a valid type hint, though PHP does not support type hinting for a generic object. What about everything else? Here is a peculiar example of the limitations of PHP’s type hinting:
<?php
function stringTest(string $string) {
    echo $string;
}
stringTest("definitely a string");
Catchable fatal error: Argument 1 passed to stringTest() must be an instance of string, string given, called in typehint.php on line 42 and defined in typehint.php on line 39
You’re not the first think “What is this madness? I gave you a string instance, and yet you complain it must be an instance of string!” It’s alright. It happens to the best of us. In fact, it can be quite a confusing error message at first glance. stringTest() is not looking for a string, it is looking for an instance of a string class. Scalar data types, such as strings or integer values, are not supported in PHP’s type hinting. But it’s okay! If you need to raise an error or throw an exception when an argument is not a scalar type (like a string or integer), you can do perform basic validation to serve this purpose using functions like is_string() or is_int().

The Scalar Wars

There has been a bit of controversy regarding the addition of scalar PHP type-hinting in PHP 5.4. Those who oppose the change argue that this support would go against the fundamental designs of PHP. PHP is considered to be a weak typed language. In essence, this means that PHP does not require you to declare data types. Variables still have data types associated with them but you can do radical things like adding a string to an integer without resulting in an error. In May of 2010 support for scalar type hinting was added to the PHP trunk. But because of community response this feature will not make its way into the 5.4 release.

Summary

Type hinting is a technique introduced into PHP for object-oriented programming (specifically for identifying the type of a caught exception). I encourage you to read more about working with objects here. Image via Carlos E. Santa Maria / Shutterstock

Frequently Asked Questions (FAQs) about Type Hinting in PHP

What is the importance of type hinting in PHP?

Type hinting in PHP is a significant feature that allows developers to specify the expected data type of an argument in a function declaration. It enhances the robustness of the code by ensuring that functions receive values of the correct type. This leads to fewer errors and bugs in the code, making it more reliable and easier to debug. It also improves code readability, making it easier for other developers to understand the code’s functionality.

Can I use type hinting with all data types in PHP?

PHP supports type hinting for several data types, including objects, arrays, interfaces, callable, and iterable. However, it’s important to note that PHP did not support scalar type hinting (int, float, string, and bool) until version 7.0. From PHP 7.0 onwards, you can use type hinting for all data types.

What happens if the data type of a passed argument does not match the type hint?

If the data type of a passed argument does not match the type hint in the function declaration, PHP will throw a “Fatal Error.” This error will halt the execution of the script, preventing any further processing. This is why it’s crucial to ensure that the correct data types are passed to functions.

How does type hinting work with class inheritance in PHP?

In PHP, type hinting can be used with class inheritance. If a function expects an argument of a certain class type, it will also accept instances of subclasses of that class. This is because a subclass is a specific type of its parent class, and therefore satisfies the type hint.

Can I use type hinting with PHP’s built-in functions?

No, type hinting in PHP can only be used in user-defined functions. PHP’s built-in functions do not support type hinting. However, these functions usually have internal mechanisms to handle different data types.

What is strict mode in PHP type hinting?

Strict mode in PHP type hinting is a feature introduced in PHP 7.0. When strict mode is enabled, PHP will enforce the exact matching of data types as per the type hint. If the data type of a passed argument does not match exactly with the type hint, PHP will throw a “Fatal Error,” even if the argument could be coerced to the correct type.

How can I enable strict mode in PHP?

To enable strict mode in PHP, you need to declare ‘declare(strict_types=1);’ at the top of your PHP file. This declaration must be the very first statement in your script.

What is the difference between weak and strict mode in PHP type hinting?

The difference between weak and strict mode in PHP type hinting lies in how PHP handles type mismatches. In weak mode, PHP will try to coerce the passed argument to the correct data type if possible. In contrast, in strict mode, PHP will not attempt to coerce the value and will throw a “Fatal Error” if the data types do not match exactly.

Can I use type hinting for function return values?

Yes, from PHP 7.0 onwards, you can use type hinting for function return values. This feature allows you to specify the expected data type of a function’s return value, enhancing the reliability and readability of your code.

What is nullable type hinting in PHP?

Nullable type hinting is a feature introduced in PHP 7.1. It allows you to specify that a function argument or return value can be of a specified type or null. To make a type hint nullable, prepend the type name with a question mark (?). For example, ‘?string’ means the value can be a string or null.

Amanda SteigerwaltAmanda Steigerwalt
View Author

Amanda Steigerwalt is a twenty-something software engineer living in Mountain View, CA. Her passion for web development began at a young age and so far has served her well in life. When she's not at work coding, she can often be found at home coding her own personal projects. Amanda also enjoys motorcycles, circus arts, and exploring Mountain View. One day she really, really hopes to get a puppy.

Intermediate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week