Using a variable from another condition in PHP

百般思念 提交于 2019-12-04 06:54:26

问题


I have this code:

if(!isset($_GET["act"]))
{
    $display->display("templates/install_main.html");
    if(isset($_POST["proceed"]))
    {
        $prefix = $_POST["prefix"];
    }
}

if($_GET["act"] == "act")
{
    echo $prefix;
}

Basically I've made a similar question before, thing is, HOW can I make the variable accessible? please mention if there is any way to do so, even with changing the way it's done (someone told me it's possible with a class but not quite sure how it can be done), or any other way to make it accessible.

Thanks!


回答1:


PHP's variable scope is function-level. $prefix would be available in your second if() IF the other if()'s evaluated to true and actually executed that $prefix = ... code.

e.g.

if (true) {
    $foo = 'bar'; // always executes
}
if (false) {
    $baz = 'qux'; // never executes
}
echo $foo; // works just fine
echo $baz; // undefined variable, because $baz='qux' never executed.

Also note that PHP is not capable of time travel:

echo $x; // undefined variable;
$x = 'y';
echo $y; // spits out 'y'

"earlier" code will not have "later" variables available, because the code that actually creates/assigns values to those variables won't have executed yet.



来源:https://stackoverflow.com/questions/26123489/using-a-variable-from-another-condition-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!