За последние 24 часа нас посетили 51085 программистов и 1688 роботов. Сейчас ищут 1084 программиста ...

Объектные массивы в 5.3

Тема в разделе "Прочие вопросы по PHP", создана пользователем alexey_baranov, 10 дек 2010.

  1. alexey_baranov

    alexey_baranov Активный пользователь

    С нами с:
    3 фев 2009
    Сообщения:
    647
    Симпатии:
    0
    Адрес:
    Сургут
    Салют!

    Есть кто работает с массивами как с объектами? Я в доктрине нашел хорошую объектную реализацию массива, совместимую с обычными массивами пхп, можно работать, используя объектный интерфейс, и, как в груви или руби, используя замыкания map, filter и др. Кто- нибудь пробовал их или может есть другие популярные реализации?

    PHP:
    1. <?php
    2. interface Collection extends Countable, IteratorAggregate, ArrayAccess
    3. {
    4.     /**
    5.      * Adds an element at the end of the collection.
    6.      *
    7.      * @param mixed $element The element to add.
    8.      * @return boolean Always TRUE.
    9.      */
    10.     function add($element);
    11.    
    12.     /**
    13.      * Clears the collection, removing all elements.
    14.      */
    15.     function clear();
    16.  
    17.     /**
    18.      * Checks whether an element is contained in the collection.
    19.      * This is an O(n) operation, where n is the size of the collection.
    20.      *
    21.      * @param mixed $element The element to search for.
    22.      * @return boolean TRUE if the collection contains the element, FALSE otherwise.
    23.      */
    24.     function contains($element);
    25.  
    26.     /**
    27.      * Checks whether the collection is empty (contains no elements).
    28.      *
    29.      * @return boolean TRUE if the collection is empty, FALSE otherwise.
    30.      */
    31.     function isEmpty();
    32.  
    33.     /**
    34.      * Removes the element at the specified index from the collection.
    35.      *
    36.      * @param string|integer $key The kex/index of the element to remove.
    37.      * @return mixed The removed element or NULL, if the collection did not contain the element.
    38.      */
    39.     function remove($key);
    40.  
    41.     /**
    42.      * Removes the specified element from the collection, if it is found.
    43.      *
    44.      * @param mixed $element The element to remove.
    45.      * @return boolean TRUE if this collection contained the specified element, FALSE otherwise.
    46.      */
    47.     function removeElement($element);
    48.  
    49.     /**
    50.      * Checks whether the collection contains an element with the specified key/index.
    51.      *
    52.      * @param string|integer $key The key/index to check for.
    53.      * @return boolean TRUE if the collection contains an element with the specified key/index,
    54.      *          FALSE otherwise.
    55.      */
    56.     function containsKey($key);
    57.  
    58.     /**
    59.      * Gets the element at the specified key/index.
    60.      *
    61.      * @param string|integer $key The key/index of the element to retrieve.
    62.      * @return mixed
    63.      */
    64.     function get($key);
    65.  
    66.     /**
    67.      * Gets all keys/indices of the collection.
    68.      *
    69.      * @return array The keys/indices of the collection, in the order of the corresponding
    70.      *          elements in the collection.
    71.      */
    72.     function getKeys();
    73.  
    74.     /**
    75.      * Gets all values of the collection.
    76.      *
    77.      * @return array The values of all elements in the collection, in the order they
    78.      *          appear in the collection.
    79.      */
    80.     function getValues();
    81.  
    82.     /**
    83.      * Sets an element in the collection at the specified key/index.
    84.      *
    85.      * @param string|integer $key The key/index of the element to set.
    86.      * @param mixed $value The element to set.
    87.      */
    88.     function set($key, $value);
    89.  
    90.     /**
    91.      * Gets a native PHP array representation of the collection.
    92.      *
    93.      * @return array
    94.      */
    95.     function toArray();
    96.  
    97.     /**
    98.      * Sets the internal iterator to the first element in the collection and
    99.      * returns this element.
    100.      *
    101.      * @return mixed
    102.      */
    103.     function first();
    104.  
    105.     /**
    106.      * Sets the internal iterator to the last element in the collection and
    107.      * returns this element.
    108.      *
    109.      * @return mixed
    110.      */
    111.     function last();
    112.  
    113.     /**
    114.      * Gets the key/index of the element at the current iterator position.
    115.      *
    116.      */
    117.     function key();
    118.  
    119.     /**
    120.      * Gets the element of the collection at the current iterator position.
    121.      *
    122.      */
    123.     function current();
    124.  
    125.     /**
    126.      * Moves the internal iterator position to the next element.
    127.      *
    128.      */
    129.     function next();
    130.  
    131.     /**
    132.      * Tests for the existence of an element that satisfies the given predicate.
    133.      *
    134.      * @param Closure $p The predicate.
    135.      * @return boolean TRUE if the predicate is TRUE for at least one element, FALSE otherwise.
    136.      */
    137.     function exists(Closure $p);
    138.  
    139.     /**
    140.      * Returns all the elements of this collection that satisfy the predicate p.
    141.      * The order of the elements is preserved.
    142.      *
    143.      * @param Closure $p The predicate used for filtering.
    144.      * @return Collection A collection with the results of the filter operation.
    145.      */
    146.     function filter(Closure $p);
    147.  
    148.     /**
    149.      * Applies the given predicate p to all elements of this collection,
    150.      * returning true, if the predicate yields true for all elements.
    151.      *
    152.      * @param Closure $p The predicate.
    153.      * @return boolean TRUE, if the predicate yields TRUE for all elements, FALSE otherwise.
    154.      */
    155.     function forAll(Closure $p);
    156.  
    157.     /**
    158.      * Applies the given function to each element in the collection and returns
    159.      * a new collection with the elements returned by the function.
    160.      *
    161.      * @param Closure $func
    162.      * @return Collection
    163.      */
    164.     function map(Closure $func);
    165.  
    166.     /**
    167.      * Partitions this collection in two collections according to a predicate.
    168.      * Keys are preserved in the resulting collections.
    169.      *
    170.      * @param Closure $p The predicate on which to partition.
    171.      * @return array An array with two elements. The first element contains the collection
    172.      *               of elements where the predicate returned TRUE, the second element
    173.      *               contains the collection of elements where the predicate returned FALSE.
    174.      */
    175.     function partition(Closure $p);
    176.  
    177.     /**
    178.      * Gets the index/key of a given element. The comparison of two elements is strict,
    179.      * that means not only the value but also the type must match.
    180.      * For objects this means reference equality.
    181.      *
    182.      * @param mixed $element The element to search for.
    183.      * @return mixed The key/index of the element or FALSE if the element was not found.
    184.      */
    185.     function indexOf($element);
    186.  
    187.     /**
    188.      * Extract a slice of $length elements starting at position $offset from the Collection.
    189.      *
    190.      * If $length is null it returns all elements from $offset to the end of the Collection.
    191.      * Keys have to be preserved by this method. Calling this method will only return the
    192.      * selected slice and NOT change the elements contained in the collection slice is called on.
    193.      *
    194.      * @param int $offset
    195.      * @param int $length
    196.      * @return array
    197.      */
    198.     public function slice($offset, $length = null);
    199. }
     
  2. [vs]

    [vs] Суперстар
    Команда форума Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.559
    Симпатии:
    632
    да
    PHP:
    1. <?
    2. class MyArray extends ArrayObject {}
    http://ru2.php.net/ArrayObject
     
  3. Psih

    Psih Активный пользователь
    Команда форума Модератор

    С нами с:
    28 дек 2006
    Сообщения:
    2.678
    Симпатии:
    6
    Адрес:
    Рига, Латвия
    alexey_baranov
    Мне за последние 2 дня кажется, что твой аккаунт взломали и пишет другой человек :D

    ArrayObject настолько старый бойян, что всем боянам боян :) Уже давно используется вдоль и поперёк :)
     
  4. alexey_baranov

    alexey_baranov Активный пользователь

    С нами с:
    3 фев 2009
    Сообщения:
    647
    Симпатии:
    0
    Адрес:
    Сургут
    :D
    а я все время сидел на array() . А ЭррэйОбжект из ПХП ничего. Только он не 5.3 я там замыканий не увидел. а новый 5.3 ЭрэйОбжект случайно не знаешь будет?
     
  5. Psih

    Psih Активный пользователь
    Команда форума Модератор

    С нами с:
    28 дек 2006
    Сообщения:
    2.678
    Симпатии:
    6
    Адрес:
    Рига, Латвия
    alexey_baranov
    Это вообще интерфейс, а методы ты сам реализовываешь. А там замыкания как и везде уже юзаешь :)
     
  6. [vs]

    [vs] Суперстар
    Команда форума Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.559
    Симпатии:
    632
    alexey_baranov
    Можно наследовать OA, потом имплементировать нужные интерфейсы сделать замыкания
     
  7. alexey_baranov

    alexey_baranov Активный пользователь

    С нами с:
    3 фев 2009
    Сообщения:
    647
    Симпатии:
    0
    Адрес:
    Сургут
    что - то не похож он на интерфейс
    PHP:
    1. <?php
    2. $x= new ArrayObject(array(1,2,3));
    3. print_r($x);
    output:
    самому? или уже где-то выложили?
     
  8. Apple

    Apple Активный пользователь

    С нами с:
    13 янв 2007
    Сообщения:
    4.984
    Симпатии:
    2
    Покажи мне, где чего-то ещё в сети не выложили =))
     
  9. VItalijs

    VItalijs Активный пользователь

    С нами с:
    17 дек 2008
    Сообщения:
    244
    Симпатии:
    0
    Адрес:
    Рига, Латвия
    ArrayObject - класс, но он реализует ArrayAccess интерфейс( а также еще несколько), его можно реализовать и самому.