Type hinting - specify an array of objects

前端 未结 5 1923
不思量自难忘°
不思量自难忘° 2020-12-10 10:23

How can I specify the argument type as an array? Say I have a class named \'Foo\':

class Foo {}

and then I have a function that accepts tha

5条回答
  •  没有蜡笔的小新
    2020-12-10 10:54

    function getFoo()
    

    Generally, you would then have an add method that would typehint to Foo

    function addFoo( Foo $f )
    

    So, the getter would return an array of Foo's and the add method can ensure you only had Foo's to the array.

    EDIT Removed the argument from the getter. I don't know what I was thinking, you don't need an argument in a getter.

    EDIT just to display the a full class example:

    class FooBar
    {
        /**
         * @return array
         */
        private $foo;
    
        public function getFoo()
        {
            return $foo;
        }
    
        public function setFoo( array $f )
        {
            $this->foo = $f;
    
            return $this;
        }
    
        public function addFoo( Foo $f )
        {
            $this->foo[] = $f;
    
            return $this;
        }
    }
    

    You generally, and probably shouldn't, have the setter method since you have the add method to help ensure $foo is an array of Foo's but it helps illustrate what is going on in the class.

提交回复
热议问题