嗯,我知道你可能不是在尋找這個,但它已經很晚了,我很無聊。
聲明:這是一個不好主意。
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';
這是一個簡單的任務。大多數程序員認爲這個陳述沒有副作用。這意味着除了創建一個新變量之外,這個語句在執行流程中沒有任何變化。
我們的MyString
或mysprintf
違反了這個假設。 什麼應該是一個簡單的任務,現在有副作用。它以最糟糕的方式違反了程序員的期望。
結果字符串實際上沒有它從建成了部分記憶。如果你想要其中一個部分是不同的,那麼你必須重新構建它,就像你使用函數一樣。 – ShiraNai7
我只是爲你寫一個函數來達到這個目的,但我是盲目的,並沒有看到你的。我會說這是做到這一點的最好方法。 – Beans
這種類型的任務基本上是什麼功能。 *根據條件返回一些東西*堅持功能。 – worldofjr