Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

php - Type hinting in class variables

<?php

namespace Sandbox;

class Sandbox {

    private ConnectorsISandboxConnector $connection;

    public function __construct(ConnectorsISandboxConnector $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 SandboxSandbox and not SandboxConnectorsISandboxconnector, why?

question from:https://stackoverflow.com/questions/18956588/type-hinting-in-class-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PHP 7.3 and below does not support typed properties. You could only define a variable as below:

class Sandbox {
    private $connection;

However, to help editors understand your code, you may use a @var tag to document the expected type of the property:

class Sandbox {
    /** @var ConnectorsISandboxConnector */
    private $connection;

Update

PHP 7.4.0

Thanks @Manuel for mentioning the new update, PHP 7.4 now introduces typed properties according to PHP RFC: Typed Properties 2.0.

Property type declarations support all type declarations supported by PHP, with the exception of void and callable. Any class or interface name, stdClass, scalar and compound types, references to parent and own objects are also supported.

class Sandbox {
    public int $id;
    public string $name;
    private ConnectorsISandboxConnector $connection;
}

Note: keep an eye on side effects such as uninitialised state and inheritance strict rules.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...