-1

次のようなPHP関数があります。

function count_nutrient_value($input){
 // some difficult operations here
 return $output; // this is a string
}

私はこのように使用しています(例):

$print .= 'This nutrient is giving you '.count_nutrient_value(40).' percent.';

ここでの問題は、関数から別の値を返す必要があることです。つまり、数値が上昇しているか下降しているかという情報です。だから私は関数を変更します:

function count_nutrient_value_new($input){
 // some difficult operations here
 return array($output,$status); // this is an array, obviously
}

しかし、これを行うことができなくなったため、関数を簡単に使用できなくなりました。

$print .= 'This nutrient is giving you '.count_nutrient_value_new(40).' percent.';

ただし、代わりに、次のように、より多くの行に展開する必要があります。

$return = count_nutrient_value_new(40);
$print .= 'This nutrient is giving you '.$return[0].' percent.';

この状況の解決策はありますか? これは:

A) 関数から配列を返さない (ただし、別の方法で問題を解決する)
B) 配列を返し、コード内で関数を使用するより簡単な方法を見つける
C) その他?

4

6 に答える 6

2

一部のコードが壊れる可能性があるため、関数のシグネチャを変更することは避けます。代わりに、新しい関数を追加して呼び出したいと思います。

とにかく、ここで説明した方法で関数を変更する必要がある場合は、配列の代わりにユーティリティ クラスを使用します。

  • クラスには $count と $status の 2 つの属性があり、それらを公開するかどうかは便宜上の問題です。あなたの場合、公開属性は問題ないと思います。
  • このクラスは、古いコードとの互換性を維持するために __toString() メソッドを実装することもできます。

何かのようなもの :

class nutrientResults {

    public $status = SOME_DEFAULT_VALUE;
    public $count = 0;

    public function __construct($count, $st = SOME_DEFAULT_VALUE) {
         $this->count = $count;
         $this->status = $st;
    }

    public function __toString() {
        return (string) $this->count;
    }

}

それで :

function count_nutrient_value($input){
    // some difficult operations here
    return new nutrientResults($count, $status);
}

$print .= 'This nutrient is giving you '.count_nutrient_value(40).' percent.';
// as usual..., so backwards compatibility maintained
于 2013-06-20T06:58:58.807 に答える
0

出力パラメータを使用できます。

function count_nutrient_value($input, &$out1, &$out2){
 // some difficult operations here
 $out1 = $output[0];
 $out2 = $output[1];
 return $output[0]; // return the same
}

$print .= 'This nutrient is giving you '.count_nutrient_value(40, $o1, $o2).' percent.';
// Do other things with $o1 and $o2.

PHP 5 では、オプションのパラメーターも使用できます。

function count_nutrient_value($input, &$out1 = '', &$out2 = ''){
 // some difficult operations here
 $out1 = $output[0];
 $out2 = $output[1];
 return $output[0]; // return the same
}

// Call without out parameters
$print .= 'This nutrient is giving you '.count_nutrient_value(40).' percent.';
于 2013-06-20T07:01:20.940 に答える
0

$outputプロパティとして $status と を持つ小さなクラスに関数を変換します。

class count_nutrient_value() {
public $output;
public $status;
function __construct($input) {
   // Do complicate stuff here
   $this->output = $output_result;
   $this->status = $status_result;
}
}

それからあなたはすることができます

$nutrient = new count_nutrient_value($input);
$print .= 'This nutrient is giving you '.$nutrient->output.' percent.';
于 2013-06-20T07:01:42.267 に答える