Permalink
Browse files

Create assoc class and modify Arr::forge to use it

  • Loading branch information...
1 parent deddbb9 commit 50ceb406f4a84cb26bcc794b8488e4865d1d7f01 Alastair McGowan-Douglas committed Oct 26, 2011
Showing with 36 additions and 7 deletions.
  1. +19 −7 classes/arr.php
  2. +17 −0 classes/assoc.php
View
@@ -5,10 +5,10 @@
* functions, as well as adding a few that PHP should support but which are
* presumably too complex for PHP users to understand.
*
- * This is currently intended to represent an ordinal array, but a future
- * development will allow non-numeric keys to work, given that PHP's associative
- * arrays have an unfathomable internal ordering and hence it should be
- * workable.
+ * The Arr class represents an ordinal array, which means that keys are
+ * restricted to positive integers. It also means the array is both ordered and
+ * contiguous. This allows array access by negative index to do the expected
+ * thing and count from the end of the array.
*
* @package Arr
*/
@@ -33,18 +33,30 @@ public function __construct($arr=array()) {
* a new Arr using that. Otherwise, all parameters are shoved into their
* own array and that is used instead.
*
+ * If the array looks like an ordinal array, an object of type Arr is
+ * returned; otherwise an object of type Assoc is returned. If it looks like
+ * an ordinal array but should be treated as an associative array, use
+ * \Arr\Assoc::forge() directly.
+ *
* @param mixed $var1 Either an array or not an array
* @param mixed ... More things of any type
- * @return \Arr\Arr
+ * @return \Arr\Arr, \Arr\Assoc
*/
public static function forge() {
$args = func_get_args();
if (count($args) == 1 && is_array($args[0])) {
- return new static($args[0]);
+ // This seems like a reasonable way to test whether it's a
+ // contiguous ordinal array or not!
+ if (array_keys($args[0]) == array_keys(array_values($args[0]))) {
+ return new static($args[0]);
+ }
+ else {
+ return Assoc::forge($args[0]);
+ }
}
else {
- return new static($args);
+ return new static($args);
}
}
View
@@ -0,0 +1,17 @@
+<?php
+
+/**
+ * The Assoc class is a counterpart to the Arr class, representing an
+ * associative array. It attempts to provide an interface between that which
+ * one would expect from an array while disassociating it from the inherently
+ * flawed notion that an associative array can have implicit order.
+ *
+ * This allows for associative arrays with numeric keys to be treated
+ * differently from ordinal arrays.
+ *
+ * @package Arr
+ */
+namespace Arr;
+
+class Assoc {
+}

0 comments on commit 50ceb40

Please sign in to comment.