自我重新分配PHP变量的最佳实践

时间:2015-06-11 09:05:34

标签: php

我自己重新定义$finalText的代码会在Netbeans中产生警告/通知,这让我想知道是否有更好的方法可以做到这一点?

警告:

You should use only:
1 assignment(s) (4 used)
to a variable:
$finalText
to avoid accidentally overwriting it and make your code easier to read.
----
(Alt-Enter shows hints)

我的代码:

$languageCode = 'en';
$finalText = 'Very large text with myLeftSquareBracket variables in it to be replaced later.';
$finalText = $this->applyFormatting($finalText, $languageCode);
$finalText = str_replace('myLeftSquareBracket', '[', $finalText);

1 个答案:

答案 0 :(得分:3)

你可以这样做:

$finalText = str_replace('myLeftSquareBracket', '[', $this->applyFormatting('Very large text with myLeftSquareBracket variables in it to be replaced later.', $languageCode));

但正如评论中所述,这变得不那么可读了。

或另一种解决方案是使用几个不同的变量名称:

$languageCode = 'en';
$finalText1 = 'Very large text with myLeftSquareBracket variables in it to be replaced later.';
$finalText2 = $this->applyFormatting($finalText1, $languageCode);
$finalText3 = str_replace('myLeftSquareBracket', '[', $finalText2);
unset($finalText1, $finalText2);

但它真的有用吗?

我的建议是这样离开。