Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Function Arguments: Array of Objects of a Specific Class

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!

like image 399
Niko Efimov Avatar asked Jun 29 '11 15:06

Niko Efimov


People also ask

How do you pass an array of objects as an argument?

Passing array of objects as parameter in C++ Array of Objects:It is an array whose elements are of the class type. It can be declared as an array of any datatype. Syntax: classname array_name [size];

Can we pass array as argument in PHP?

You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside. function sendemail($id, $userid){ // ... } sendemail(array('a', 'b', 'c'), 10);

Can you have an array of objects in PHP?

We can use the array() function to create an array of objects in PHP. The function will take the object as the arguments and will create an array of those objects. We can create objects by creating a class and defining some properties of the class. The properties of the class will have some values.

Can a function take an array as an argument?

If we pass an entire array to a function, all the elements of the array can be accessed within the function. Single array elements can also be passed as arguments. This can be done in exactly the same way as we pass variables to a function.


1 Answers

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.

like image 197
Jon Avatar answered Sep 18 '22 17:09

Jon