1

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

<?php
class C {}

function f(array C $c) {
    /* use $c[1], $c[2]... */
}
8
  • There's no need to declare any type for $c, you can directly do function f($c){ ... }, given that $c is an array of Class C objects. Commented Jan 22, 2017 at 18:26
  • 1
    No way for this. Or create a class like CCollection which will store collection of C objects Commented Jan 22, 2017 at 18:26
  • you dont need to add "array" in your parameter. All you need to do is add what type of object you are passing, in this case is class C as so: function f(C $c) { .. } Commented Jan 22, 2017 at 18:36
  • @CodeGodie argument must be array of C objects Commented Jan 22, 2017 at 18:37
  • Ahh.. gotcha @u_mulder thanks for the clarificaion Commented Jan 22, 2017 at 18:40

1 Answer 1

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

PHP7.1 supports an iterable type hint: wiki.php.net/rfc/iterable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.