【问题标题】:PHP: Type hinting in namespaces not working?PHP:命名空间中的类型提示不起作用?
【发布时间】:2015-12-14 10:57:27
【问题描述】:

我正在尝试在使用命名空间时使用 PHP 5.6 进行一些类型提示,但我不断收到如下错误:

PHP 可捕获的致命错误:参数 1 传递给 NS\MyClass::__construct() 必须是字符串的实例,字符串 给定的,调用的 /Users/用户名/路径/MyClass.php 在第 9 行并定义在 /Users/用户名/路径/MySubClass.php 第 52 行

代码基本上是这样的:

<?php namespace NS;

class MySubClass extends MyClass {
    public function __construct(string $mystring) {
        parent::__construct($mystring);
    }
}

?>

<?php namespace NS;

class MyClass {
    public function __construct() {
        // do stuff
    }
}

?>

所以当我用类似这样的字符串调用子类的构造函数时

$x = new \NS\MySubClass("hello");

出现错误。 它也不适用于

public function __construct(\string $mystring) {

如何在命名空间中输入基本类型?

【问题讨论】:

    标签: php type-hinting


    【解决方案1】:

    在 PHP 5.6 中无法输入提示字符串。 PHP 7 中添加了对该功能的支持。

    More info on typehinting for functions in PHP.

    【讨论】:

      猜你喜欢
      • 2016-05-22
      • 2012-09-16
      • 2013-07-11
      • 2013-07-21
      • 2016-09-14
      • 2019-03-24
      • 2013-07-13
      • 2013-02-07
      相关资源
      最近更新 更多