Oliver Williams Oliver Williams - 3 months ago 5x
PHP Question

PHP classes conforming a parameter passed to a method to a class - Type Hinting

This is a simple question but I do not know the terms for this so thought this question would be useful.

In PHP, I have seen this construct:

Class Class_A{
function sampleMethod(Class_B $a){
$a = /* some value */;
$obj = new Class_A;
$return = $obj->sampleMethod($a);

The part I don't understand is prefixing
in the argument to method

Questions I have are:

  • What is the correct terminology for this method? (So I can research)

  • Are we declaring the variable to be Class_B?

  • Does
    have to be an object of Class_B already? Are there conditions under which the variable type of
    will not be compatible with Class_B?

-- Edit: the term I was seeking was Type Hinting --


It looks like you are talking about type hinting (or actually as it has now been named type declaration). To answer your questions:

  1. Type Declaration or Type Hinting. Named so because you are essentially hinting at what type of data this argument needs to be.

  2. We are declaring that the specified argument needs to be either that scalar type (built in data types like array, string, int...etc) or an instance of the specified class or interface.

  3. Yes, it does have to be of the specific type or a class that implements/extends that type.

Here is the example from the manual linked above that I think does a good job of showing this:

class C {}
class D extends C {}

// This doesn't extend C.
class E {}

function f(C $c) {
    echo get_class($c)."\n";

f(new C); //output: C
f(new D); //output: D
f(new E); //output: fatal error argument must be an instance of C

As you can see, the declaration required class C to be passed in. Passing in the instance of C works as expected. Passing in D works as well because D extends C and so it is considered a valid instance of C even with the extra methods/properties that D might include. Passing in E fails with a fatal error because it doesn't relate to C in any way.