2

次の変数があります。

$argument = 'blue widget';

次の関数で渡します。

widgets($argument);

widgets 関数には 2 つの変数があります。

$price = '5';
$demand ='low';

私の質問は、次のことをどのように行うことができるかです。

 $argument = 'blue widget'.$price.' a bunch of other text';
 widgets($argument);
 //now have function output argument with the $price variable inserted where I wanted.
  • 関数に $price を渡したくない
  • 価格は関数内で利用可能になります

これを行う適切な方法はありますか、それともデザインを再考する必要がありますか?

4

6 に答える 6

5

私の頭の上から、これを行うには2つの方法があります。

  1. 2 つの引数を渡す

    widget($initText, $finalText) {
        echo $initText . $price . $finalText;
    }
    
  2. プレースホルダーを使用する

    $placeholder = "blue widget {price} a bunch of other text";   
    widget($placeholder);
    
    function widget($placeholder) {
         echo str_replace('{price}',$price,$placeholder);
    }
    // within the function, use str_replace
    

例を次に示します: http://codepad.org/Tme2Blu8

于 2012-06-13T16:07:58.327 に答える
3

ある種のプレースホルダーを使用してから、関数内で置き換えます。

widgets('blue widget ##price## a bunch of other text');

function widgets($argument) {
    $price = '5';
    $demand = 'low';

    $argument = str_replace('##price##', $price, $argument);
}

実際の動作はこちら: http://viper-7.com/zlXXkN

于 2012-06-13T16:09:03.273 に答える
2

私はお勧めしpreg_replace_callbackます。このメソッドを使用することで、キャプチャされた値を参照として簡単に使用して、置換対象を決定できます。無効なキー (おそらく入力ミスの原因) に遭遇した場合、これにも対応できます。

// This will be called for every match ( $m represents the match )
function replacer ( $m ) {
    // Construct our array of replacements
    $data = array( "price" => 5, "demand" => "low" );
    // Return the proper value, or indicate key was invalid
    return isset( $data[ $m[1] ] ) ? $data[ $m[1] ] : "{invalid key}" ;
}

// Our main widget function which takes a string with placeholders
function widget ( $arguments ) {
    // Performs a lookup on anything between { and }
    echo preg_replace_callback( "/{(.+?)}/", 'replacer', $arguments );
}

// The price is 5 and {invalid key} demand is low.
widget( "The price is {price} and {nothing} demand is {demand}." );

デモ: http://codepad.org/9HvmQA6T

于 2012-06-13T16:20:18.563 に答える
2

次のように、変数のプレースホルダーを作成します。

$argument = 'blue widget :price a bunch of other text';

widget()関数では、辞書配列を使用してstr_replace()結果文字列を取得します。

function widgets($argument) {
  $dict = array(
    ':price'  => '20',
    ':demand' => 'low',
  );
  $argument = str_replace(array_keys($dict), array_values($dict), $argument);
}
于 2012-06-13T16:10:23.670 に答える
1

はい、できます。関数内でグローバルを使用します。

$global_var = 'a';
foo($global_var);

function foo($var){
    global $global_var;

    $global_var = 'some modifications'.$var;
}
于 2012-06-13T16:06:53.057 に答える
-1

関数内で単に引数を変更するのではなく、引数を変更してウィジェット関数から返すことを検討してください。$argument が関数を読まなくても変更されていることは、コードを読んでいる人にとってより明確になります。

$argument = widget($argument);

function widget($argument) {
    // get $price;
    return $argument . $price;
}
于 2012-06-13T16:08:53.990 に答える