PHP Type hinting

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • function f(ClassName $param) {}
  • function f(bool $param) {}
  • function f(int $param) {}
  • function f(float $param) {}
  • function f(string $param) {}
  • function f(self $param) {}
  • function f(callable $param) {}
  • function f(array $param) {}
  • function f(?type_name $param) {}
  • function f() : type_name {}
  • function f() : void {}
  • function f() : ?type_name {}

Remarks

Type hinting or type declarations are a defensive programming practice that ensures a function's parameters are of a specified type. This is particularly useful when type hinting for an interface because it allows the function to guarantee that a provided parameter will have the same methods as are required in the interface.

Passing the incorrect type to a type hinted function will lead to a fatal error:

Fatal error: Uncaught TypeError: Argument X passed to foo() must be of the type RequiredType, ProvidedType given



Got any PHP Question?