3

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)
    {
    }
}
dewd
  • 4,380
  • 3
  • 29
  • 43

3 Answers3

4

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.

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
  • You guys make this too easy. 20 minutes of various searches on google for php function bareword and the like with nothing. Even a response on here telling someone that using a bareword like this is unheard of in programming! A quick post on here, and within 10 minutes... bang! :) – dewd May 05 '13 at 13:43
  • I probably used hours on my own figuring out and understanding stuff like this. When something is hard won it becomes easy to explain it back. – Sverri M. Olsen May 05 '13 at 13:48
  • Very true indeed. I find things I get very quickly disappear from my knowledge just as quick if they aren't used. I'll remember this one! :) – dewd May 05 '13 at 13:57
2

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.

Techie
  • 44,706
  • 42
  • 157
  • 243
0

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

chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
  • Yes, documentation is great when you know what you're looking for! Obviously, I didn't know to look for type hinting. Thanks for the link. – dewd May 05 '13 at 13:39
  • Cheers @dewd. Hope you got your answer. Make sure to accept the answer whichever you like from all. – chandresh_cool May 05 '13 at 13:41