我可以在php中为传递的函数参数添加变量值吗?

abs*_*ntx 2 php

我有以下变量:

$argument = 'blue widget';
Run Code Online (Sandbox Code Playgroud)

我通过以下函数传递:

widgets($argument);
Run Code Online (Sandbox Code Playgroud)

小部件函数有两个变量:

$price = '5';
$demand ='low';
Run Code Online (Sandbox Code Playgroud)

我的问题是如何做到以下几点:

 $argument = 'blue widget'.$price.' a bunch of other text';
 widgets($argument);
 //now have function output argument with the $price variable inserted where I wanted.
Run Code Online (Sandbox Code Playgroud)
  • 我不想将$ price传递给该函数
  • 价格在功能内部可用

有什么声音可以做到这一点,还是我需要重新考虑我的设计?

xbo*_*nez 5

在我的头顶,有两种方法可以做到这一点:

  1. 传递两个参数

    widget($initText, $finalText) {
        echo $initText . $price . $finalText;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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
    
    Run Code Online (Sandbox Code Playgroud)

这是一个例子:http://codepad.org/Tme2Blu8