给出以下示例:
public function replaceMyText($search, $replace, &$content)
{
$newContent = str_replace($search, $replace, $content, $count = 1)
$content = $newContent;
}
这会导致Warning
只能通过引用传递变量吗?如果是这样,我无法完全理解原因。
在将其传递给$content
函数之前,应该将str_replace
分配给另一个变量吗?
答案 0 :(得分:0)
编辑
请尝试以下代码:
function replaceMyText($search, $replace, $content)
{
$newContent = str_replace($search, $replace, $content,$count=1);
return $newContent;
}
$searchValue = "test";
$replaceWith = "magic trick";
$actualContent = "This is a test.";
$replaced = replaceMyText($searchValue,$replaceWith,$actualContent);
echo $replaced;
答案 1 :(得分:0)
<?php
function replaceMyText($search, $replace, &$content)
{
$newContent = str_replace($search, $replace, $content, $count = 1);
$content = $newContent;
}
replaceMyText("123", "456", "123456");
在不使用变量的情况下使用此功能会导致致命错误
Fatal error: Only variables can be passed by reference in /usercode/file.php on line 8
因为
不应通过引用传递其他表达式,因为结果是不确定的。
来自http://php.net/manual/en/language.references.pass.php
您只能以此使用
$a = "123456";
replaceMyText("123", "456", $a);
echo $a;
对不起,我英语不好。希望它能对您有所帮助。