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

查看:32
本文介绍了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天全站免登陆