2

PHP では、いくつかの引数を参照によって関数に渡す必要があります。同様の動作のために2つの異なるメソッドを書きたくありません。したがって、引数で動作を選択する必要があります。しかし、参照によってnullを渡すことはできません。そこで、ダミー配列を作成しました。

だから私はそれを実行します

    $temp[0]=-1;
    $this->doSomething($bigIds, $temp);
or
    $temp[0]=-1;
    $this->doSomething($temp, $smallIds);


public function doSomething(&$bigIds, &$smallIds) {
        if ($bigIds[0] != -1) {
             // make some thing
        }
        if ($smallIds[0] != -1) {
             // make some thing
        }
}

これを行うためのより良い/エレガントな方法はありますか?

4

2 に答える 2

2

たとえば、@ ad7sixがコメントで言っていることなど、やりたいことがたくさんある可能性があります。また、ある種の設定と1つの配列だけを指定することもできます。

public function doSomething(&$bIds, $mode) {
   switch($mode){
      case 1: do smallthing;break;
      case 2: do bigthing;break;
      case 3: do both;break;
      default: do nothing;break;
}

それはすべてあなたが本当に必要とするものに依存します

于 2012-05-03T20:14:32.860 に答える
2

列挙型を提案しますが、これはPHPです。だからこれはあなたのためにそれをするべきです:

class YourClass
{
    const DoSomethingSmall = 0;
    const DoSomethingBig = 1;

    public function doSomething(&$ids, $actionType) {
        // can also use a switch here
        if($actionType == self::DoSomethingSmall) {
            // do small
        }
        else if($actionType == self::DoSomethingBig) {
            // do big
        }
    }
}

次に、次のことができます。

$this->doSomething($bigIds, self::DoSomethingBig);
$this->doSomething($smallIds, self::DoSomethingSmall);

クラスの外からあなたが使用することができYourClass::DoSomethingBigYourClass::DoSomethingSmall

于 2012-05-03T20:15:27.313 に答える