简体   繁体   中英

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 $a with Class_B in the argument to method sampleMethod() .

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 $a have to be an object of Class_B already? Are there conditions under which the variable type of $a 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:

<?php
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM