【问题标题】:How new object working in the latest version of PHP新对象如何在最新版本的 PHP 中工作
【发布时间】:2019-02-19 18:41:32
【问题描述】:

根据 PHP 7.2 文档

引入了一种新类型 object,可用于任何对象的(逆变)参数类型和(协变)返回类型。

下面的例子已经给出

<?php

function test(object $obj) : object
{
   return new SplQueue();
}

test(new StdClass());

谁能详细说明逆变参数和协变返回类型的含义以及这个新对象的工作原理

【问题讨论】:

    标签: php type-hinting php-7.2 static-typing


    【解决方案1】:

    object 在代码中的两个位置都可以返回通用对象,即任何类型的实例。 (如您的示例所示)

    否则需要:

    <?php
    
    function test(StdClass $obj) : SplQueue
    {
       return new SplQueue();
    }
    
    test(new StdClass());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 2015-08-10
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 2018-10-12
      相关资源
      最近更新 更多