1Up
1Up

Reputation: 1044

Strange PHP Syntax - String before $variable? What is this?

I came across a block of code in a class like this:

...
public function __construct(
    PDO $pdo,
    CommonSqlQueries $csq
) {
...

What is the meaning of the string such as PDO before the variable $pdo? I don't even know what this sort of syntax is called, much less how to research it.

Upvotes: 1

Views: 98

Answers (2)

shellco
shellco

Reputation: 536

This is called type hinting.

Functions are [since PHP5] able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4)."

http://php.net/manual/en/language.oop5.typehinting.php

Upvotes: 2

raina77ow
raina77ow

Reputation: 106483

It's called type hinting (and it was introduced in PHP 5):

Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

Failing to satisfy the type hint results in a catchable fatal error. In your case, it'll occur if the constructor function will be called with something other than PDO and CommonSqlQueries objects as the first and the second param respectively.

Upvotes: 6

Related Questions