gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:16:45 25 4
gpt4 key购买 nike

$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com