PHP函数参数:特定类的对象数组 [英] PHP Function Arguments: Array of Objects of a Specific Class

查看:205
本文介绍了PHP函数参数:特定类的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受特定类成员的函数:

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

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

我想创建另一个函数,该函数采用My_Page对象的数组:

I'd like to make another function that takes an array of My_Page objects:

public function addPages($pages)
{
  // ...
}

我需要确保$ pages数组的每个元素都是My_Page的实例.我可以使用foreach($pages as $page)进行操作并检查instance of,但是我可以在函数定义中以某种方式指定该数组必须是My_Page对象的数组吗?即兴创作,例如:

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

谢谢!

推荐答案

否,无法直接执行.您可以尝试使用此聪明"技巧:

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)
{
    //
}

但是我不确定是否值得所有麻烦.如果addPage本身有用,那将是一个很好的方法.

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.

这篇关于PHP函数参数:特定类的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆