为什么即使我的代码是这样的:
if ( ! function_exists('get_values')){
global $str;
function getValues($getThem, $tpar, $vpiso, $tcomi, $tgas, $ttotal){
$totalPares = $tpar;
$ventasPiso = $vpiso;
$totalComisiones = $tcomi;
$totalGastos = $tgas;
$totalTotal = $ttotal;
$str = $totalPares . "," . $ventasPiso . "," . $totalComisiones . "," . $totalGastos . "," . $totalTotal;
return $str;
}
function getEm(){
return $str;
}
}
我无法覆盖$ str的值。它总是打印 - 如果我试图回显它,并且在“getEm”函数内它表示它是一个未定义的变量。
这是codeigniter框架中的帮助文件。
修改
仍然给我这个错误:
遇到PHP错误
严重性:注意
消息:未定义的变量:str
文件名: 助手/ helper_common_functions_helper.php
行号:15
答案 0 :(得分:1)
global $str;
您需要研究变量范围。函数有自己的作用域,除非你在开始时global $variable
访问该函数之外的变量。还请注意,使用全局变量是“nono”,应该不惜一切代价避免使用。
function getValues($getThem, $tpar, $vpiso, $tcomi, $tgas, $ttotal){
global $str;
$totalPares = $tpar;
$ventasPiso = $vpiso;
$totalComisiones = $tcomi;
$totalGastos = $tgas;
$totalTotal = $ttotal;
$str = $totalPares . "," . $ventasPiso . "," . $totalComisiones . "," . $totalGastos . "," . $totalTotal;
return $str;
}
答案 1 :(得分:1)
如果您想要在某个范围内保持状态,您应该从中创建一个类。不推荐global
class MyClass {
private $str = "a";
public function getValues($getThem, $tpar, $vpiso, $tcomi, $tgas, $ttotal){
$totalPares = $tpar;
$ventasPiso = $vpiso;
$totalComisiones = $tcomi;
$totalGastos = $tgas;
$totalTotal = $ttotal;
$str = $totalPares . "," . $ventasPiso . "," . $totalComisiones . "," . $totalGastos . "," . $totalTotal;
return $str;
}
public function getEm(){
return $this->str;
}
}
然后你需要在使用它之前实例化(当然),但你要保持你的范围清洁
$x = new MyClass;
echo $x->getEm();
如果仅使用静态属性和方法创建类,则不需要对其进行实例化(MyClass:getEm()
)。
答案 2 :(得分:0)
全局变量看起来错位,也许这有帮助:
if ( ! function_exists('get_values')){
function getValues($getThem, $tpar, $vpiso, $tcomi, $tgas, $ttotal){
global $str; ##### <- place it here
$totalPares = $tpar;
$ventasPiso = $vpiso;
$totalComisiones = $tcomi;
$totalGastos = $tgas;
$totalTotal = $ttotal;
$str = $totalPares . "," . $ventasPiso . "," . $totalComisiones . "," . $totalGastos . "," . $totalTotal;
return $str;
}
function getEm(){
global $str; ##### <- place it here
return $str;
}
}
旁注:我真的不知道codeigniter的设计有多好,但使用名为$str
的全局变量听起来像是在惹麻烦。给它一个更好地反映它属于什么以及它代表什么的名称。 $getValues_Helper_String
虽然字符串不多说。 Some tips on finding a name