Type hinting in class variables

2019-04-17 20:14发布

<?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条回答
我想做一个坏孩纸
2楼-- · 2019-04-17 21:15

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;
查看更多
登录 后发表回答