dongza1708 2011-06-21 23:41
浏览 11
已采纳

无法理解一种行为

Why is it that even though my code is like this:

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;
    }
}

I can't override the value of $str. It always prints ¨a¨ if I try to echo it, and inside the "getEm" function it says it's an undefined variable.

This is the helper file in the codeigniter framework.

EDIT

which still gives me this error:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: str

Filename: helpers/helper_common_functions_helper.php

Line Number: 15

  • 写回答

3条回答 默认 最新

  • douchuitang0642 2011-06-21 23:43
    关注
    global $str;
    

    You need to research variable scoping. Functions have their own scope unless you have global $variable at the start to access the variables outside that function. Please also note, using global variables is a "nono" and should be avoided at all cost.

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?