PHP 函数中的类型声明(typehint)

PHP type declaration (typehint) in function

据我所知,没有办法(即使在 PHP 7 中)强制函数将其参数的类型提示作为对象数组。

我认为可以通过将另一个对象定义为 Traversable 来实现这一点,这将是数组中所有 MyObject 的容器,并将类型提示设置为该对象可遍历。

但是,如果我能做到这一点,那就太酷了:

public function foo(MyObject[] $param) {}

所以我的问题是,PHP 没有实施这个有什么原因吗?

我不太明白你的问题,但如果你想在对象中插入数据,你可以这样做:

<?php
class Insert
{
public $myobject = array();

public function foo($insert_in_object, $other_param_in_object) {
$this->myobject[] = $insert_in_object;
$this->myobject[] = $other_param_in_object;
return $this->myobject;
}

}

$start = new Insert();
$myobject = $start->foo('dog', 'cat');
var_dump($myobject)
?>

你也可以

$arrYourObjectType = new YourObjectType[];

然后如果对象数组是您的 return 函数类型,在您的 phpdoc 中键入提示 return 值,在 phpdoc在你的函数之上:

/**
* @param $whatever
* @return array ...$arrYourObjectType
**/
public function someFunction($whatever){
  $arrYourObjectType[] = new YourObjectType[];
  $x=0;
  foreach($arrValues as $value)
  {
      $objYourObjectType = new YourObjectType();
      $objYourObjectType->setSomething($value[0])
          ->setSomethingElse($value[1]);
      (and so on)
      //we had to set the first element to a new YourObjectType so the return
      //value would match the hinted return type so we need to track the 
      //index
      $arrYourObjectType[$x] = $objYourObjectType;
      $x++;
  }
  return $arrYourObjectType;
}

然后在 IDE 中,例如 php 风暴,当使用包含该函数的 class 时,函数的 return 值将被视为数组您的对象(正确提示)和 IDE 将正确公开对象数组的每个元素上的对象方法。

你可以在没有这些的情况下做事 easy/dirty,但是 phpStorm 不会正确提示对象数组元素的方法。

如果将 YourObjectType 数组提供给函数...

/**
*@param YourObjectType ...$arrYourObjectType
**/
public function someFunction(YourObjectType...$arrYourObjectType){
  foreach($arrYourObjectType as $objYourObject)
  {
    $someval = $objYourObject->getSomething();//will be properly hinted in your ide
  } 
}

都是关于输入和检索对象数组时的省略号:-)

编辑:我有一些错误,因为我是凭记忆做的...更正...抱歉...