php - 我可以将变量值添加到 php 中传递的函数参数吗?

标签 php

我有以下变量:

$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 传递给函数
  • 价格在函数内部可用

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

最佳答案

在我的脑海中,有两种方法可以做到这一点:

  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

关于php - 我可以将变量值添加到 php 中传递的函数参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11018929/

相关文章:

每次页面加载时运行 PHP 登录

php - Laravel 自定义异常配置

php - 禁用主键/唯一键排序

php - 在 jQuery 链接上运行 SQL 查询

php - 尝试显示以 base64 编码的图像

php - 启用 mcrypt、soap 和 pdo_mysql

PHP - 在字符串中间添加字符(从末尾开始)

php - PHP 7.1 及更高版本的数据加密/解密

php - 使用 Doctrine2 和 Symfony2 删除表

javascript - 如何放大 slider 中的图像