PHP Function Arguments: Array of Objects of a Specific Class

后端 未结 4 1743
走了就别回头了
走了就别回头了 2020-12-17 14:49

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

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

I\'d like to make another

相关标签:
4条回答
  • 2020-12-17 15:18

    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
       }
    }
    
    0 讨论(0)
  • 2020-12-17 15:20

    You can also add PhpDoc comment to get autocomplete in IDE

        /**
         * @param My_Page[] $pages
         */
        public function addPages(array $pages)
        {
          // ...
        }
    
    0 讨论(0)
  • 2020-12-17 15:23

    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.

    0 讨论(0)
  • 2020-12-17 15:33

    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)
    
    0 讨论(0)
提交回复
热议问题