PHP Function Arguments: Array of Objects of a Specific Class

20,436

Solution 1

No, it's not possible to do directly. You might try this "clever" trick instead:

public function addPages(array $pages)
{
    foreach($pages as $page) addPage($page);
}

public function addPage(My_Page $page)
{
    //
}

But I 'm not sure if it's worth all the trouble. It would be a good approach if addPage is useful on its own.

Solution 2

You can also add PhpDoc comment to get autocomplete in IDE

    /**
     * @param My_Page[] $pages
     */
    public function addPages(array $pages)
    {
      // ...
    }

Solution 3

Instead of passing an array of objects (array(My_Page)), define your own class and require an instance of it in your function:

class MyPages { ... }

public function addPages(MyPages pages)

Solution 4

From php5.6 you can use splat operator to type hint all array elements as function params. In this case you don't have more parameters than Pages stored in array so it should work fine:

public function addPages(Page ...$pages)

More info: https://www.php.net/manual/en/migration56.new-features.php

https://lornajane.net/posts/2014/php-5-6-and-the-splat-operator

Share:
20,436
Niko Efimov
Author by

Niko Efimov

Updated on July 21, 2022

Comments

  • Niko Efimov
    Niko Efimov almost 2 years

    I have a function that takes a member of a particular class:

    public function addPage(My_Page $page)
    {
      // ...
    }
    

    I'd like to make another function that takes an array of My_Page objects:

    public function addPages($pages)
    {
      // ...
    }
    

    I need to ensure that each element of $pages array is an instance of My_Page. I could do that with foreach($pages as $page) and check for instance of, but can I somehow specify in the function definition that the array has to be an array of My_Page objects? Improvising, something like:

    public function addPages(array(My_Page)) // I realize this is improper PHP...
    

    Thanks!