PHP array of non-primitive class as function parameter

后端 未结 1 1249
再見小時候
再見小時候 2021-01-24 10:31

I am wondering (if possible) how you would declare an array of non-primitive class as a function parameter. For example



        
相关标签:
1条回答
  • 2021-01-24 11:20

    Main fact - currently you can't type hint argument as array of something.

    So you options are:

    // just a function with some argument, 
    // you have to check whether it is array 
    // and whether each item in this array has type `C`
    function f($c) {} 
    
    // function, which argument MUST be array.
    // if it is not array - error happens
    // you still have to check whether 
    // each item in this array has type `C`
    function f(array $c) {} 
    
    // function, which argument of type CCollection
    // So you have to define some class CCollection
    // object of this class can store only `C` objects
    function f(CCollection $c) {} 
    
    // class CCollection can be something like
    class CCollection 
    {
        private $storage = [];
    
        function addItem(C $item)
        {
            $this->storage[] = $item;
        }
    
        function getItems()
        {
            return $this->storage;
        }
    }
    
    0 讨论(0)
提交回复
热议问题