PHP - use of bareword in interface function declarations

252 Views Asked by At

Looking at PHP's documentation about interfaces, specifically here: PHP: Object Interfaces - Manual. The following code is given as a working example. Could someone explain what the bareword 'Baz' being declared as part of the function signature is please?

<?php
interface a
{
    public function foo();
}

interface b extends a
{
    public function baz(Baz $baz);
}

// This will work
class c implements b
{
    public function foo()
    {
    }

    public function baz(Baz $baz)
    {
    }
}
3

There are 3 best solutions below

3
On BEST ANSWER

It is called type hinting.

The baz() method expects the first argument, $baz, to be an object of the type Baz. An object's type comes from either the class that it is built from, or from an interface that it implements.

2
On

As per documentation it is called type hinting

Baz is the name of class

and hence the baz method expects the first argument, $baz, to be an object

0
On

In the class c, function baz() requires a parameter which is a object where it's class Baz. $baz is just the object name. It's used inside the function of baz().

It's called Type Hinting

PHP 5 introduces type hinting. 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.

If class or interface is specified as type hint then all its children or implementations are allowed too.

Type hints can not be used with scalar types such as int or string. Traits are not allowed either.