PHP: uso de bareword en declaraciones de funciones de interfaz

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)
    {
    }
}

preguntado el 05 de mayo de 13 a las 14:05

3 Respuestas

Se llama tipo insinuación.

Los programas 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.

contestado el 05 de mayo de 13 a las 14:05

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! :) - rocío

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

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! :) - rocío

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().

Se llama Sugerencia de tipo

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.

contestado el 05 de mayo de 13 a las 14:05

Según documentación 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

contestado el 05 de mayo de 13 a las 14:05

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. - rocío

Cheers @dewd. Hope you got your answer. Make sure to accept the answer whichever you like from all. - chadresh_cool

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.