PHP 中对象属性?中表示什么意思 哪个版本开始支持的?

2020-12-03 14:38:41 +08:00
 xoxo419
private static ?Singleton $instance = null;

https://github.com/domnikl/DesignPatternsPHP/blob/9f61e21dcf1bf3b49ef70ccc6d7849fdd82b0874/Creational/Singleton/Singleton.php#L7

1741 次点击
所在节点    PHP
4 条回复
jfcherng
2020-12-03 14:45:40 +08:00
php 7.1, 關鍵字 nullable
Still4
2020-12-03 15:05:59 +08:00
我这一般是这么用的

public function initTask($task_info, $task_num, $task_total): ?Thread

public function initTask($task_info, $task_num, $task_total): Thread

当返回结果可能为空的时候用前一个,不这么写返回空会报错
xoxo419
2020-12-03 15:25:51 +08:00
@jfcherng
@Still4

用 PHP7.2 执行报错误

```
There was 1 error:

1) DesignPatterns\Creational\Singleton\Tests\SingletonTest::testUniqueness
ParseError: syntax error, unexpected '?', expecting function (T_FUNCTION) or const (T_CONST)

/var/www/base/test/php/DesignPatterns/Creational/Singleton/Singleton.php:7
/var/www/base/test/php/DesignPatterns/Creational/Singleton/Tests/SingletonTest.php:12

```

用 php7.4 执行 OK
jfcherng
2020-12-03 15:43:36 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/731757

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX