PHP Function Arguments: Array of Objects of a Specific Class

Viewed 23110

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!

6 Answers

You can also add PhpDoc comment to get autocomplete in IDE

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

if you use the class, you can do some thing like this:

interface addPageInterface
{
   public function someThing();
}


class page implements addPageInterface
{
   public function someThing()
   {
      //for example: create a page
   }
}


class addPage
{
   public function __construct(addPageInterface $page)
   {
       //do some thing...

      return $page; //this will return just one page
   }
}


class addPages
{
   public function __construct(addPageInterface... $page)
   {
      //do some thing...

      return $page; //this will return an array which contains of page
   }
}
<?php
        
    class Page{
            public $a;
    }
        
    
    function addPages(Page ...$pages){
        foreach($pages as $page){
        
        }
    }
        
        
    $pages = [];
    $pages[]  = new Page;
    $pages[]  = new Page;
    $pages[]  = new Page;
    addPages(...$pages);
    
?>

i think its better way

Related