【问题标题】:How to specify the type of the parameter in PHP [duplicate]如何在PHP中指定参数的类型[重复]
【发布时间】:2013-01-28 00:45:48
【问题描述】:

可能重复:
PHP type-hinting to primitive values?

说,我创建了一个名为

的函数
retrieveCount($count){
   return ++$count;
}

只是一个简单的例子。如何将函数设置为仅接受整数类型? 在 Java 或其他语言中,我们有:

public int retrieveCount(int count){
   return ++count;
}

有没有办法在 PHP 中做同样的事情?我在文档中读到,对于 OOP,PHP 具有复杂结构的类型提示,例如对象、数组、接口等,但对于标量类型(int、string)则没有。

真的是这样,我们不能指定类型吗?

谢谢

【问题讨论】:

  • 见:type hinting
  • @JohnConde "类型提示不能用于标量类型,例如 int 或 string。"
  • 那么他们如何对预定义的函数进行类型提示?

标签: php casting


【解决方案1】:

PHP 没有直接的标量类型提示可能性。但是你可以通过检查函数内部的类型来模拟它并触发适当的错误:

function retrieveCount( $count )
{
    if( !is_int( $count ) )
    {
        // I believe E_USER_WARNING is the appropriate error level
        // equivalent to what PHP issues itself on type hint errors
        trigger_error(
            'Argument 1 passed to retrieveCount() must be an integer',
            E_USER_WARNING
        );
    }

    return ++$count;
}

【讨论】:

    【解决方案2】:

    没有直接的方法可以做到这一点,但是您可以像这样在函数中强制类型:

    function retrieveCount($count) {
        $count = intval($count);
        return ++$count;
    };
    

    查看类似功能strvalfloatval...

    【讨论】:

    • 但这不会返回 2,同时引发 E_Notice 但是,这真的是解决问题的好方法吗?也就是说,如果你碰巧传递了一个对象......
    • 好吧,如果类型错误,您可以使用is_int() 并自己抛出错误。
    【解决方案3】:

    为确保函数接收整数类型,您需要像这样调用is_int()

    function retriveCount( $count ){
      if( !is_int( $count ) )
        return 0; // or whatever you want errors to return
    
      return ++$count;
    }
    

    或者,如果您希望能够处理由数字组成但不一定是数字的字符串,您可以执行以下操作:

    function retriveCount( $count ){
      if( (int)$count != $count )
        return 0; // or err value
    
      return ++$count; // will be integer type
    }
    

    阅读为什么在Type Juggling documentation 中返回值将是一个没有任何类型转换的整数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-04
      • 2023-03-04
      • 2019-11-04
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 2018-10-01
      • 2013-07-09
      相关资源
      最近更新 更多