douni1396 2016-04-14 16:34
浏览 68
已采纳

我们可以确定php中数组元素的返回类型吗?

Is it possible to dertermine the elements type of the returning array in a function?

For example, if the elements should be floats:

class test{
    /**
     * This should return an array containing float values,
     * but I get a fatal error instead
     */
    public static function doStuff() : float[] {
        return [ 10.3, 12.8 ];
    }
}
  • 写回答

1条回答 默认 最新

  • douyanqu9722 2016-04-14 16:55
    关注

    Unfortunately you can't type-check the contents of an array like that.

    If you really insist on doing this, you could create your own collection class that wraps around the array and ensures the type of its elements:

    class FloatCollection
    {
        private $array = [];
    
        public function __construct($array = [])
        {
            foreach ($array as $value) {
                $this->add($value);
            }
        }
    
        public function add(float $value)
        {
            $this->array[] = $value;
        }
    
        ...
    }
    

    Then you can type check for that:

    public static function doStuff() : FloatCollection
    {
        return new FloatCollection([10.3, 12.8]);
    }
    

    But it might be a lot of unnecessary work for what you're trying to achieve.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题