PHP Function Arguments: Array of Objects of a Specific Class

别等时光非礼了梦想. 提交于 2020-02-27 15:03:06

问题


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!


回答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.




回答2:


You can also add PhpDoc comment to get autocomplete in IDE

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



回答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)



回答4:


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
   }
}


来源:https://stackoverflow.com/questions/6523062/php-function-arguments-array-of-objects-of-a-specific-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!