用于多维数组的PHP自定义DataType

时间:2014-07-08 11:33:20

标签: php multidimensional-array reference associative-array custom-data-type

我正在使用多维关联数组,主要用于配置数据和引入" breadcrumbs"进入多维数组的使用。 基本思想:我的类被设计为处理一维(平面)面包屑数组作为多维关联数组中某些值的参考指南。面包屑的每个递增索引基本上是数组内部的更深层,直到找到最后一个级别和关联键并在递归中到达。 E.g:

$myArray = array(
  'firstLevel' => array(
    'secondLevel' => array(
      'myValue' => 42
    ),
    'anotherLevel' => array(
      'anotherValue' => 13
    )
  )
);
$myBreadcrumb = array('firstLevel', 'secondLevel', 'myValue');
$fancyClass = new \someNamespace\fancyArrayProcessingClass($myArray);
$myValue = $fancyClass->getValueForBreadcrumb($myBreadcrumb);

如果要求,我也会发布处理面包屑的示例,但由于我定制了自定义数据类型,因此我发现它不在主题之内。 它变得令人厌倦,并且始终是编码和#34; Wrapper"类,实现的类或其他类型的构造,以通过breadcrumb使数组可导航。我想知道是否有办法将真正的新DataTypes引入到PHP中,可以像实际的DataTypes一样处理。我对这个概念的良好语法的想法:

$myArray = navigableArray(
  'firstLevel' => array(
    'secondLevel' => array(
      'myValue' => 42
    ),
    'anotherLevel' => array(
      'anotherValue' => 13
    )
  )
);
$myBreadcrumb = array('firstLevel', 'secondLevel', 'myValue');
$myValue = $myArray[$myBreadcrumb];

甚至更直观地使用xpath风格的字符串:

$myArray = navigableArray(
  'firstLevel' => array(
    'secondLevel' => array(
      'myValue' => 42
    ),
    'anotherLevel' => array(
      'anotherValue' => 13
    )
  )
);
$myValue = $myArray['firstLevel/secondLevel/myValue'];

我知道PHP文档中有一句话说的是"开发人员永远不需要将他们自己的DataTypes引入PHP"但是AFAIK没有理由说明为什么它和它一样为什么开发人员 - 与几乎所有其他语言不同 - 无法引入完全自定义的数据类型。

编辑: 对于任何好奇的人:我找到了另一条路线,标准的php类" ArrayAccess"您可以使PHP对象的行为类似于实际的数组。着名的" Judy" class included" ArrayAccess"和#34;迭代器"并且完全适合我在这个问题中寻找的东西。

http://php.net/manual/de/class.arrayaccess.php

http://php.net/manual/de/class.judy.php

1 个答案:

答案 0 :(得分:1)

根据您的用例,我建议您查看PHP的SPL迭代器。特别是Recursive Iterator接口或RecursiveArrayIterator实现。这些迭代器本身构建为PHP,非常快,许多允许您使用本机PHP函数(如foreach(),for(),count()等)访问它们。

然后,您可以扩展其中一个SPL Iterator接口,以创建自己的自定义类,为您提供特定于Breadcrumb需求的功能。 FWIW,我认为开发人员不应该在PHP中创建他们自己的本机数据类型(因为你不能)但是非常鼓励用PHP类创建自定义类型。过度使用原生数组。