簡體   English   中英

我可以在php中為傳遞的函數參數添加變量值嗎?

[英]Can I add a variable value to a passed function parameter in php?

我有以下變量:

$argument = 'blue widget';

我通過以下函數傳遞:

widgets($argument);

小部件函數有兩個變量:

$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傳遞給該函數
  • 價格在功能內部可用

有什么聲音可以做到這一點,還是我需要重新考慮我的設計?

在我的頭頂,有兩種方法可以做到這一點:

  1. 傳遞兩個參數

     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

使用某種占位符,然后在函數中替換它:

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

為您的變量創建一個占位符,如下所示:

$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);
}

我會鼓勵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

是的你可以。 在函數中使用全局。

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

function foo($var){
    global $global_var;

    $global_var = 'some modifications'.$var;
}

考慮更改參數,然后從widget函數返回它,而不是簡單地在函數內更改它。 對於閱讀代碼的人來說,更清楚的是$ argument被修改而不必閱讀該函數。

$argument = widget($argument);

function widget($argument) {
    // get $price;
    return $argument . $price;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM