質問

Can somehow a variable defined in a part of an IF be accessible in another part of the same IF?

Ex:

if ($a == 1)
{
  $b = "ABC";
}
elseif ($a == 2)
{
 echo $b;
}

In functions i use global $variable but in IF-statements i dont know.

The reason why i'm asking this its because i'm making a registration page step-by-step.
It means that i need to check for that If-statement a lot of times and in my final step i need to gather all variables from all IFs.

役に立ちましたか?

解決

There are no "global" variables the way you understand them.
All the PHP variables doomed to die with all the PHP script after it's execution.

You need some storage to keep your variables between requests.
PHP sessions is a good choice.

他のヒント

The IF statement in PHP does not change variable scope - unlike a function. So anything you do in an IF will be visible outside the if as long as you stay in the same scope. You don't need to use GLOBAL. Indeed, the global scope should be used as little as possible.

The global statement simply widens the scope allowing PHP to "see" things that would otherwise be hidden. You still need to understand variable scoping though since the interactions of scope are not always obvious. I suggest going back to read the excellent PHP documentation. You'll probably need to read through it a few times and experiment a bit before it clicks.

The issue with your code is that, unless it is inside a loop that you are not showing, you will never see the value of $b because the if statement is a branch and you will only ever execute one of the branches never more than 1.

Another issue with your example is that you are using linked if statements and this would be much better written as:

switch ($a) {
    case 1:
        $b = "ABC";
        break;
    case 2:
        # $b will ALWAYS be empty unless you set it BEFORE the switch OR
        # you loop back to the switch AFTER $a=1
        echo $b;
        break;
    default:
        echo "i is not equal to 1 or 2";
}

See: http://php.net/manual/en/control-structures.switch.php

This form is much clearer to read and much simpler & more robust as the number of cases increases.

Well no look $a only have 1 value it maybe 1 or 2 or something else if its 1 then $b = ABC and it never comes in your elseif condition and if $a is 2 then it never entered in your first condition but yes you can define $b before condition.

$b = "something";
if ($a == 1)
{
  $b = "ABC"; // $b is ABC if $a = 1
}
elseif ($a == 2)
{
 echo $b; // output : something, if $a  = 2
}
$b = Null
if ($a == 1)
{
  $b = "ABC";
}
elseif ($a == 2)
{
 echo $b;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top