php - 我可以用 PHP 中的另一个变量修改字符串中的变量吗?

标签 php variables

$pet ='dog'; 
$action='My '. $pet . 'likes to run.'; 
//The part I would like to modify
$pet ='cat'; 
//Modify the $pet variable inside the $action variable 
//after it has been defined.
echo $action;

这将输出:我的狗喜欢运行

我可以让它输出:我的猫喜欢运行

我也尝试过:

$pet ='dog';  
$action=sprintf('My %s likes to run.', $pet);
$pet ='cat';
echo $action;

我确实知道这可以通过创建一个带有如下参数的函数来实现。但我是一个 php 初学者,对其他方法感到好奇。

function action($pet = "dog") {
    $p = 'My'. $pet . 'likes to run.';
    return $p;
}
$pet = 'cat';
echo action($pet);

最佳答案

嗯,我知道你可能不是在找这个,但是已经很晚了而且我很无聊。

免责声明:这是一个坏主意

class MyString
{
    private $format, $pet;

    public function __construct($format, &$pet)
    {
        $this->format = $format;
        $this->pet = &$pet;
    }

    public function __toString()
    {
        return sprintf($this->format, $this->pet);
    }
}

$myString = new MyString('This is my little %s, cool huh?', $pet);

$pet = 'cat';
echo $myString."\n";

$pet = 'dog';
echo $myString."\n";

$pet = 'goldfish';
echo $myString."\n";

输出:

This is my little cat, cool huh?
This is my little dog, cool huh?
This is my little goldfish, cool huh?

演示:https://3v4l.org/XmUEZ

基本上,此类在其字段中存储对 $pet 变量的引用。因此,当 $pet 变量更新时,类中的引用也会更新。


另一个很好的措施:

function mysprintf($format, &$variable)
{
    return function() use ($format, &$variable) {
        return sprintf($format, $variable);
    };
}

$print = mysprintf('This is my little %s, cool huh?', $pet);

$pet = 'cat';
echo $print()."\n";

$pet = 'dog';
echo $print()."\n";

$pet = 'goldfish';
echo $print()."\n";

https://3v4l.org/KJTKj

(Ab)使用闭包来保存引用。可能更糟。


您可能会问,为什么这是一个坏主意?

仅考虑以下陈述:

$pet = 'goldfish';

这是一个简单的作业。大多数程序员认为该语句没有副作用。这意味着除了创建一个新变量之外,该语句不会改变执行流程中的任何内容。

我们的MyStringmysprintf违反了这个假设。 本来应该是简单的赋值,现在却产生了副作用。它以最糟糕的方式违反了程序员的期望。

关于php - 我可以用 PHP 中的另一个变量修改字符串中的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39988560/

相关文章:

javascript - $ 未在 javascript 中定义 ajax 请求

php - 将 curdate() - 间隔替换为 $variable - 间隔

PHP <-> JavaScript 通信 : Am I stuck with ASCII?

c# - 变量声明的部分名称

javascript - JavaScript 中的全局变量可在函数内更改

c++ - 1/a*a 和 1*a/a 的区别

python - 我如何 'declare' 一个空字节变量?

php - 在 PHP 中将数组更改为数据库查询

php - 如何使用php-mysql在1个月后自动将数据库表中的状态从0更改为3

php - Facebook PHP SDK 4.0 登录