【问题标题】:Verify if parameter passed to function is array not验证传递给函数的参数是否不是数组
【发布时间】:2023-03-31 20:27:01
【问题描述】:

假设我有函数

public function test($dataid){
    .........   
}

现在我只想在$dataid 必须是数组时运行函数。如果不是,那就不行了

ifi 传递了一个字符串,例如 test("string") 它不会运行。

我知道is_array(),但还有其他解决方案吗?

如果 value 为空,它将自动转换为数组

【问题讨论】:

  • 除了is_array,你可以使用类型检查..
  • 公共函数测试((array)$dataid){
  • 我如何输入检查?
  • And if value is empty it will be automatically convert to array ?
  • 如果值为空,为什么要将值转换为数组?

标签: php function oop


【解决方案1】:

你可以使用PHP的type hinting

public function(array $arg){
 ....
}

但这不会将$arg 转换为数组,您可以允许NULL 像这样的值:

// PHP 7.1 and above
public function(?array $arg){
 ....
}

// Or set the default value to NULL
public function(array $arg = NULL){
 ....
}

或者,如果$arg 是一个数组,则直接使用is_array($arg) 将返回TRUE

要将值转换为数组,您可以type cast它:

(array) '';   // Gives an array with one element equal to ''
(array) NULL; // Gives an empty array
(array) 0;    // Gives an array with one element equal to 0

【讨论】:

    【解决方案2】:

    类型提示会起作用,但是 under version restrictions.

    一种原始的方法。

    if(gettype($dataid) === 'array'){
        // Do the needful here
    }
    

    还是很可靠的……

    【讨论】:

      【解决方案3】:

      这就是你想要的:

      if (is_array($array) or ($array instanceof Traversable)) {
          ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-29
        • 2016-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-22
        • 1970-01-01
        • 2018-06-03
        相关资源
        最近更新 更多