开发者

Returning a variable that is deeply nested in an if else control structure?

How would I return a variable that is deeply nested inside an if else structure, for use in another function that alters the program flow from the result of the returned variable in the first function? This is the basic structure of the program, the if and else开发者_开发百科 statements can contain more if else statements that is why I used the word deeply. How would I use the variable in the second function?

e.g.

function this_controls_function_2($flow) {
    if($flow == 1) {
       $dothis = 1;
       return $dothis;
    }
    else {
       $dothis = 2;
       return $dothis;
    }
}

function this_is_function_2() {
    if($dothis == 1) {
       //DO SOMETHING
    }
    else {
       //DO SOMETHING
    }
} 


function this_is_function_2($flow) {
    $dothis = this_controls_function_2($flow);
    if($dothis == 1) {
       //DO SOMETHING
    }
    else {
       //DO SOMETHING
    }
}

Or, if you want to call the first function outside of function 2:

function this_is_function_2($dothis) {
    if($dothis == 1) {
       //DO SOMETHING
    }
    else {
       //DO SOMETHING
    }
}

$dothis = this_controls_function_2($flow);
this_is_function_2($dothis);


Well either you simply read the returned variable directly from the function:

function this_is_function_2() {
    if(this_controls_function_2($flow) == 1) {
       //DO SOMETHING
    }
    else {
       //DO SOMETHING
    }
}

Or you mark the variable as global:

function this_controls_function_2($flow) {
    global $dothis;

    if($flow == 1) {
       $dothis = 1;
       return $dothis;
    }
    else {
       $dothis = 2;
       return $dothis;
    }
}

function this_is_function_2() {
    global $dothis;

    if($dothis == 1) {
       //DO SOMETHING
    }
    else {
       //DO SOMETHING
    }
}

For that, the order of the function calls must fit:

this_controls_function_2($flow);

/* ... */

this_is_function_2();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜