By Amanda Steigerwalt

Type Hinting in PHP

By Amanda Steigerwalt

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:

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?

$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:

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:

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.


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

  • A word to notice. Unlike a really strongly typed safe languages that needs to be compiled before using such as Java, PHP actually never checks that the class you typehinded actually exists before you invoke it. If it’s a good or bad feature, I don’t know but after all, PHP is a scripting language :)

  • Awesome little bit of knowledge. I already knew about type hinting but didn’t know why scalar type hinting wasn’t supported it seemed counter-intuitive. Looking forward to PHP 6

  • Alice Young

    I find it bizarre that such a hideous language as PHP, with its kitchen-sink of functions, has to also optionally pretend it’s a strongly typed language. (I write in Ruby and Java, not PHP.)

    • Stefan Froelich

      It is rather unfortunate that you have to be like that, but I read an article yesterday (quite dated) but makes perfect sense and good reading.
      It describes your sort of mindset
      . This is good as well
      and actually talks about the type system . Quite educative and sensible I should add. I think I discovered a gold mine of ancient knowledge.

      I agree with the articles I should say. I program in php, python, javascrpt and yes, java. Each has their place in my life and I use them wherever I deem them best. I won’t try to use php in my browser or to create GUIs (though it does that). I love js and its peculiar brand of inheritance.
      One reason php is popular is because of its ease of use and the fact that it has borrowed quite a lot from other languages it deems good. If users want to have type hinting, they get it. Everyone is happy. It helps.
      One reason I love php is its type system. Simple and easy to get into. You easily understand the conversions and you get used to them. Type hinting was great for me especially since they didn’t mess with my bool to int or string conversion. I guess that’s why scalar type hinting was never added. Yes I want my objects to be of the right type, but I want to use my strings or ints or bools as any of them.
      I loved java when I started (coming from a background of scripting).
      The strictness in the typing was sweet, though infuriating at first. However, I got used to it and enjoyed the benefits they brought. That’s not to say I don’t like php the way it is, but hey, I’m making websites and html and css are already complicated enough. I love to be able to put together a few lines and my code runs.

      All I am trying to say is that, we need to enjoy the benefits of languages out there and use each to maximize out output. None is better than the others, but each excels at a task more than the others.

  • Great article! I have been using PHPDoc in order to know which types are used when using auto-complete in the php ide I’m using. Such as /** @var MyClass */ private $item;

  • Of course you could specify/cast the values data type within the class you are type hinting, giving you the best of both worlds. But then you are relying on the class you are type hinting to actually do the job. Meh!

  • I wish that PHP did support type hinting for scalars. I also wish that PHP method signatures required specifying a return type. My back ground is mostly PHP and front-end (CSS, JS, jQuery, etc) but last year I started getting into Java and the Android SDK. Coming from a loosely-typed language like PHP, it seemed obnoxious and tedious at first to have to specify return data types and argument data types. However, once I got used to it I quickly realized the benefit. It’s like built-in automatic documentation. You can look at a class constructor or a method signature and right away you know how to use it, even if the author provided no documentation. Plus if you think about, half the time when something breaks in PHP it’s because the wrong data is being passed. “I don’t get why it’s not a working. I did a var_dump() and the string I’m passing has the correct data. Oh wait, it’s supposed to be an integer?”

    Just sayin’…

Get the latest in PHP, once a week, for free.