Question

I know some of the beauty of PHP comes from loose typing, but I want to make a PHP class with strictly-typed, object-oriented functions.

I tried what I thought would work:

... [index.php]

24: include './documentation-builder.php';
25: $builder = new DocBuilder('Documentation');

... [documentation-builder.php]

5:  class DocBuilder
6:  {
7:      function __construct(string $title)
8:      {
9:          $this->title = $title;
10:     }
11: }

But I got the following error:

Catchable fatal error: Argument 1 passed to DocBuilder::__construct() must be an instance of string, string given, called in \path\to\index.php on line 25 and defined in \path\to\documentation-builder.php on line 5

The fact that is says "Argument 1 ... must be an instance of string, string given" makes me think I am close, but forgot to set a flag somewhere.

How do I require strict typing on my PHP functions?

Was it helpful?

Solution

Only type hinting for classes and arrays are supported at this time.

Type hints can not be used with scalar types such as int or string. Resources and Traits are not allowed either.

source

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top