class name before function arguments

I often see some “programming gurus” use strange advanced syntax such as this one:

somefunction(\WP_Query $query)
{
    ....
}


This is a piece of php code. You know, usually php does not require class name before function arguments. You expect the following code:

somefunction($query)
{
    ....
}

Why does the programming guru add the class name WP_Query before the function parameter $query? More strange, why is a backslash \ added before the class name? I cannot help worshiping the programming guru. In fact, you can remove the class name including the backslash from the code without a problem. The class name added before a function argument is called type hinting, which is used to force the caller to use a parameter value that is an instance of that class. If you do not use a value of that class when calling the defined function, php will throw a fatal error(Uncaught TypeError) and abort.

As to the backslash before the class name, it is a namespace indicator. The \ means global namespace. So, if there is another definition of WP_Query in current namespace, php will take the global one instead of the class in current namespace.

 

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Leave a Reply