Интерфейс PHP, SPL, ArrayAccess

Я пытаюсь понять идею интерфейса ArrayAccess,

Я не понимаю, что такое каждый метод, если эти методы (функции) являются «встроенными» функциями, а интерфейс ArrayAccess (также «встроенный») только «убедитесь», что я собираюсь реализовать эти «встроенные» методы (функции )

Я пытаюсь понять, что делает каждая из этих функций с нашим кодом «За кулисами».

function offsetSet($offset, $value); function offsetGet($offset); function offsetUnset($offset); function offsetExists($offset); 

Если я понимаю, что ArrayAccess является встроенным интерфейсом, который содержит уплотнения для реализации, когда мы их реализуем, мы используем только ссылки на встроенные функции, я буду рад, если кто-то может помочь мне в этом.

Solutions Collecting From Web of "Интерфейс PHP, SPL, ArrayAccess"

Если вы реализуете этот интерфейс, то объект действует как массив. например, если $foo является экземпляром класса, реализующего ArrayAccess :

$foo['bar'] = 42 вызывает offsetSet('bar', 42) .

echo $foo['bar'] вызывает offsetGet('bar') .

unset($foo['bar']) вызывает offsetUnset('bar') .

isset($foo['bar']) вызывает offsetExists('bar') .

Вы никогда явно не вызываете функции offset * самостоятельно. Это происходит неявно, когда вы обращаетесь к объекту как к массиву.

Сравнивая ArrayAccess с SimpleXMLElement (внутренним классом, не реализующим его), мне также было любопытно. Интерфейс хорошо документирован в руководстве уже, поэтому я хотел бы выделить некоторые различия в специфике со смещенными типами.

Но в первую очередь это примерный пример реализации класса, реализующего ArrayAccess дает результат при доступе:

 /** * ArrayAccess Example */ class ExampleArrayLikeAccess implements ArrayAccess { /** * Whether a offset exists * * @link http://php.net/manual/en/arrayaccess.offsetexists.php * @param mixed $offset - An offset to check for. * @return boolean true on success or false on failure. * * The return value will be casted to boolean if non-boolean was returned. */ public function offsetExists($offset) { echo " - offsetExists(", $this->varString($offset),")\n"; } /** * Offset to retrieve * * @link http://php.net/manual/en/arrayaccess.offsetget.php * @param mixed $offset The offset to retrieve. * @return mixed Can return all value types. */ public function offsetGet($offset) { echo " - offsetGet(", $this->varString($offset),")\n"; } /** * Offset to set * * @link http://php.net/manual/en/arrayaccess.offsetset.php * @param mixed $offset The offset to assign the value to. * @param mixed $value The value to set. * @return void */ public function offsetSet($offset, $value) { echo " - offsetSet(", $this->varString($offset), ", ", $this->varString($value), ")\n"; } /** * Offset to unset * @link http://php.net/manual/en/arrayaccess.offsetunset.php * @param mixed $offset The offset to unset. * @return void */ public function offsetUnset($offset) { echo " - offsetUnset(", $this->varString($offset),")\n"; } /** * helper to give a variable dump in form of a string */ private function varString($var) { ob_start(); var_dump($var); return trim(strtr(ob_get_clean(), ["\n" => '', "\r" => '']), ' {}'); } } 

Запуск некоторых примеров использования с ним. Я оставил записи в форме комментариев. Это должно быть довольно самоочевидно:

 $like = new ExampleArrayLikeAccess(); /* offsetExists */ // indexes/keys that behave similar to PHP arrays: isset($like[1]); # integer stay integer # offsetExists(int(1)) isset($like['1']); # string like an integer - converted to integer # offsetExists(int(1)) isset($like['01']); # string unlike an integer - stays string # offsetExists(string(2) "01") isset($like[TRUE]); # booleans are converted to integer # offsetExists(bool(true)) // indexes/keys that differ to PHP arrays: isset($like[1.1]); # a float stays a float (double) # offsetExists(double(1.1)) isset($like[NULL]); # NULL stays NULL # offsetExists(NULL) isset($like[array()]); # array stays array # offsetExists(array(0)) isset($like[$like]); # object stays object # offsetExists(class SxeLikeAccess#2 (0)) /* offsetGet */ // indexes/keys behave the same as with offsetExists: $like[1]; # offsetGet(int(1)) $like['1']; # offsetGet(int(1)) $like['01']; # offsetGet(string(2) "01") // ... /* offsetSet */ $like[1] = 'value'; # index/key behaves the same as with offsetExists # offsetSet(int(1), string(5) "value") $like[] = 'value'; # index/key is NULL # offsetSet(NULL, string(5) "value") $like[NULL] = 'value'; # index/key is NULL # offsetSet(NULL, string(5) "value") /* offsetUnset */ unset($like[1]); # index/key behaves the same as with offsetExists unset($like[NULL]); # same for NULL с $like = new ExampleArrayLikeAccess(); /* offsetExists */ // indexes/keys that behave similar to PHP arrays: isset($like[1]); # integer stay integer # offsetExists(int(1)) isset($like['1']); # string like an integer - converted to integer # offsetExists(int(1)) isset($like['01']); # string unlike an integer - stays string # offsetExists(string(2) "01") isset($like[TRUE]); # booleans are converted to integer # offsetExists(bool(true)) // indexes/keys that differ to PHP arrays: isset($like[1.1]); # a float stays a float (double) # offsetExists(double(1.1)) isset($like[NULL]); # NULL stays NULL # offsetExists(NULL) isset($like[array()]); # array stays array # offsetExists(array(0)) isset($like[$like]); # object stays object # offsetExists(class SxeLikeAccess#2 (0)) /* offsetGet */ // indexes/keys behave the same as with offsetExists: $like[1]; # offsetGet(int(1)) $like['1']; # offsetGet(int(1)) $like['01']; # offsetGet(string(2) "01") // ... /* offsetSet */ $like[1] = 'value'; # index/key behaves the same as with offsetExists # offsetSet(int(1), string(5) "value") $like[] = 'value'; # index/key is NULL # offsetSet(NULL, string(5) "value") $like[NULL] = 'value'; # index/key is NULL # offsetSet(NULL, string(5) "value") /* offsetUnset */ unset($like[1]); # index/key behaves the same as with offsetExists unset($like[NULL]); # same for NULL 

Основные отличия от стандартных массивов PHP заключаются в том, что вы можете использовать не только integer и string в качестве смещений.