[英]How can I split PHP up and reuse parts of it?
I'm trying to split a line of PHP up, the reason being I don't actually always need some of the code and so that I can reuse parts of it. 我试图将PHP分成几行,原因是我实际上并不总是需要某些代码,因此我可以重用其中的一部分。
The main reason I'm doing this is because the currency I get shows more digits for some currencies eg 1.2562 instead of 1.25, so I want to use the substr function only on certain GET's and be able to modify it for other GET's. 我这样做的主要原因是因为我获得的货币对某些货币显示更多位数,例如1.2562,而不是1.25,所以我只想对某些GET使用substr函数,并能够为其他GET修改它。
http://prntscr.com/6ttw8o http://prntscr.com/6ttw8o
symbol is always required, substr isn't, $converter always required, end part of substr isn't however it can change, new currency is required. 符号始终是必需的,substr不是必需的,$ converter始终是必需的,substr的结尾部分不是必需的,但是它可以更改,需要新的货币。
$symbol[2] . substr(($converter->convert($defaultCurrency, $newCurrency) * 1), 0, 4) . " <b>" .$newCurrency. "</b>";
I've tried doing this with explode, however I'm not entirely sure how to do it as I have never really had to split anything up before so I'm a little puzzled on how to go about it. 我已经尝试过使用explode进行此操作,但是由于我之前从未真正拆分过任何东西,因此我不太确定该怎么做,因此我对如何执行它感到有些困惑。
Once the code has gone through the GET checking which is the current one set, I want it to grab the specified split up code pieces and then output it. 一旦代码通过了GET检查(当前集合),我希望它抓取指定的拆分代码段,然后输出。
Put your code in a function like this: 将您的代码放在这样的函数中:
function formatCurrency($symbol, $converter, $defaultCurrency, $newCurrency, $factor=1.0, $suffix="", $substrChars=0) {
if($substrChars>0) {
return $symbol . substr(($converter->convert($defaultCurrency, $newCurrency) * $factor), 0, $substrChars) . $suffix . " <b>" . $newCurrency. "</b>";
} else {
return $symbol . ($converter->convert($defaultCurrency, $newCurrency) * $factor) . $suffix . " <b>" . $newCurrency. "</b>";
}
}
If you call it without the $substrChars
parameter, it will omit the substr()
call, otherwise it will strip all but the first $substrChars
characters: 如果不带$substrChars
参数调用它,它将忽略substr()
调用,否则它将除$substrChars
前$substrChars
字符外的所有字符:
if( $_GET['currency'] === "GBP" ){
$newCurrency = $_GET['currency'];
$string = formatCurrency($symbol[1], $converter, $defaultCurrency, $newCurrency, 2.0, ".00", 0);
} elseif( $_GET['currency'] === "USD" ){
$newCurrency = $_GET['currency'];
$string = formatCurrency($symbol[2], $converter, $defaultCurrency, $newCurrency, 1.0, "", 4);
}
This solution is very readable because you immediately see the difference between the two branches in the conditional statement. 该解决方案非常易读,因为您可以立即在条件语句中看到两个分支之间的差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.