Type hinting in class variables

2019-04-17 21:06发布

问题:

<?php

namespace Sandbox;

class Sandbox {

    private Connectors\ISandboxConnector $connection;

    public function __construct(Connectors\ISandboxConnector $conn) {
        $this->connection = $conn;
    }

}

?>

For the above code I'm getting the following error:

Parse error: syntax error, unexpected 'Connectors' (T_STRING), expecting variable (T_VARIABLE)

When I remove the type hinting and var_dump that $connection variable, it will be private Sandbox\Sandbox and not Sandbox\Connectors\ISandboxconnector, why?

回答1:

PHP does not support type hinting on fields. So define a variable as below:

class Sandbox {
    private $connection;

To help editors understand your code you could use a @var tag to document the expected type of the field:

class Sandbox {
    /** @var Connectors\ISandboxConnector */
    private $connection;