我有以下变量:
$argument = 'blue widget';
我传入以下函数:
widgets($argument);
widgets 函数中有两个变量:
$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 传递给函数
- 价格在函数内部可用
有什么好的方法可以做到这一点,还是我需要重新考虑我的设计?
最佳答案
在我的脑海中,有两种方法可以做到这一点:
传入两个参数
widget($initText, $finalText) { echo $initText . $price . $finalText; }
使用占位符
$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
关于php - 我可以将变量值添加到 php 中传递的函数参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11018929/