Type hinting in PHP 7 - array of objects

后端 未结 7 1862
迷失自我
迷失自我 2020-12-08 03:36

Maybe I missed something but is there any option to define that function should have argument or return for example array of User objects?

Consider the following cod

相关标签:
7条回答
  • 2020-12-08 04:31

    A fairly simple approach is to create your own array type which works with PHP's built-in functions such as foreach, count, unset, indexing, etc. Here is an example:

    class DataRowCollection implements \ArrayAccess, \Iterator, \Countable
    {
        private $rows = array();
        private $idx = 0;
    
        public function __construct()
        {
        }
    
        // ArrayAccess interface
    
        // Used when adding or updating an array value
        public function offsetSet($offset, $value)
        {
            if ($offset === null)
            {
                $this->rows[] = $value;
            }
            else
            {
                $this->rows[$offset] = $value;
            }
        }
    
        // Used when isset() is called
        public function offsetExists($offset)
        {
            return isset($this->rows[$offset]);
        }
    
        // Used when unset() is called
        public function offsetUnset($offset)
        {
            unset($this->rows[$offset]);
        }
    
        // Used to retrieve a value using indexing
        public function offsetGet($offset)
        {
            return $this->rows[$offset];
        }
    
        // Iterator interface
    
        public function rewind()
        {
            $this->idx = 0;
        }
    
        public function valid()
        {
            return $this->idx < count($this->rows);
        }
    
        public function current()
        {
            return $this->rows[$this->idx];
        }
    
        public function key()
        {
            return $this->idx;
        }
    
        public function next()
        {
            $this->idx++;
        }
    
        // Countable interface
    
        public function count()
        {
            return count($this->rows);
        }
    }
    

    Usage example:

    $data = new DataRowCollection(); // = array();
    $data[] = new DataRow("person");
    $data[] = new DataRow("animal");
    

    It works just like a traditional array, but it is typed like you wanted it to be. Very simple and effective.

    0 讨论(0)
提交回复
热议问题