如何在PHP trait中使用数组引用声明抽象方法


How to declare abstract method with array reference in PHP trait?

当试图使用一个具有抽象方法声明的trait的类时,并且该抽象方法声明的参数类型为引用数组

我得到以下错误:

致命错误:MyTrait和MyClass在MyClass的组合中定义了相同的属性($foo)。然而,定义不同,被认为是不相容的。类在MyClass 中组成

如何在trait中声明抽象方法,以要求展示类只接受数组引用作为输入参数?

Trait和展示类中指向数组引用的形参的适当语法是什么?

(更新)例子:

<?php
const LOCATION_PRECISION = 7;
const LOCATION_LAT = '40.7591523';
const LOCATION_LNG = '-73.9777136';
trait Geocodes
{
    protected $recast = [];
    protected $precision = LOCATION_PRECISION;
    abstract function reCast(array &$payload);
}
class Location
{
    use Geocodes;
//FATAL: can't override here!
//protected $recast = [
//    'lat' => ['index' => 'lat', 'type' => 'double'],
//    'lng' => ['index' => 'lng', 'type' => 'double']
//];
protected $lat = LOCATION_LAT;
protected $lng = LOCATION_LNG;
public function __construct()
{
   $this->precision = LOCATION_PRECISION;
   $this->recast['lat'] = ['index' => 'lat', 'type' => 'double'];
   $this->recast['lng'] = ['index' => 'lng', 'type' => 'double'];
}
public function recast(array &$payload)
{
  foreach(array_keys($payload) as $key)
  {
      var_dump($payload);
      $api_key = $this->recast[$key]['index'];
      $api_type = $this->recast[$key]['type'];
      if(! array_key_exists($api_key, $payload))
            $payload[$api_key] = bcadd($payload[$key],0,$this->precision);
  }
}
public function getLat() { return $this->lat; }
public function getLng() { return $this->lng; }
}
$loc = new Location();
$payload = ['lat' => $loc->getLat(), 'lng' => $loc->getLng()];
$loc->recast($payload);
echo PHP_EOL.print_r($payload, 1).PHP_EOL;

简短的回答是,上面问题中的代码片段确实演示了在trait的抽象函数中将对数组的引用声明为参数的正确方法。它还显示了展示类内部具体函数声明的正确语法。

我得到的错误在下面的代码片段中是可重复的,因为我试图在一个展示类的属性声明中覆盖一个特性的定义属性。碰巧属性的名字和trait的一个方法的名字是一样的,所以@Wes抓住了这个问题,尽管当时我发布的代码示例是不完整的。

是指向代码的链接,其中不工作的行被注释掉了。您可以运行代码而没有错误,然后取消问题区域的注释,它应该会失败,并显示原始帖子中的消息。