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!
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];
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With