dougou6213 2014-10-02 11:59
浏览 13

PHP中方法的多种用法[关闭]

I just wondering if is it a good practice to allow multiple datatypes as parameters of a method or function which will process the input data differently but in overall it will behave the same way and will return similar results. It is important to mention that I use PHP so I cannot overload methods and I can pass any datatype to an argument because of PHP's type juggling ability. To make easier to understand what I want, here is an example:

$form = new Form(); // This is a class which helps manage and process form fields of the $_POST
$form->fetch('user_name'); // Returns the value of the field named user_name as a string ($_POST['user_name'])
$form->fetch(); // If nothing is given as parameter it will return the whole fieldset of the form (whole content of $_POST as an array)

So my question is that is it a good practice to do this, or should I create a fetchAll() method.

Or an other example: $page->getPageDataDetails(1) will return an array containing the detailed data of page with the id:1. Like:

array(
  'id' => 1,
  'name' => 'foo'
)

While $page->getPageDataDetails() will return detailed data of all pages like:

array(
   0 =>  array(
            'id' => 1,
            'name' => 'foo'
         )

   1 =>  array(
            'id' => 2,
            'name' => 'bar'
         ) 

   2 =>  array(
            'id' => 5,
            'name' => 'something'
         )
)

So the function works with the same logic (I mean semantically the same behavior) but the format of output depends on the format of the input. Is this a good idea?

  • 写回答

2条回答 默认 最新

  • dongnvwang8591 2014-10-02 12:15
    关注

    It's depends on you and your code, because if it's a public method the good way is a create exclude method like ->getItem($Id) and ->getItems()

    But now if your code it's not in good condition and you want to create separate method to get allItems and you copy and paste whole code from one method to second and change only few lines, it's not a good practice, it's a perfect !DRY.

    I recommend to create private method like ->get() and create a public alias to this method like ->getItem($id) and ->getItems() to minify your code and get it cleanly.

    It's only my opinion

    评论

报告相同问题?

悬赏问题

  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形