Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.