Home >Backend Development >PHP Tutorial >Detailed explanation of PHP{} block-level scope

Detailed explanation of PHP{} block-level scope

小云云
小云云Original
2018-03-10 09:13:152630browse

This article mainly shares with you {} block-level scope and and && or || priority issues, I hope it can help everyone.

and && or || Priority issue:

and or has a lower priority than && || and lower than =.
Therefore $b1 = $bA and $bBThe first operation is $b1 = $bA.

$bA = true;$bB = false;$b1 = $bA and $bB;$b2 = $bA && $bB;
var_dump($b1); // $b1 = truevar_dump($b2); // $b2 = false$bA = false;$bB = true;$b3 = $bA or $bB;$b4 = $bA || $bB;
var_dump($b3); // $b3 = falsevar_dump($b4); // $b4 = true

{}Block-level scope:

In php, the internal value can be obtained outside {}. PHP has function scope, but not block scope.

if(1){    $a = 123;
}
print_r($a);  // $a = 123;
for ($i = 0; $i < 10; $i++) {    for ($j = 0; $j < 10; $j++) {        $k = 777;
    }
}
var_dump($j);//输出10var_dump($k);//输出777
$arr = [1, 2, 4];foreach ($arr as &$val) {    $val  *= 2;
}$val = [];//重新赋值$val[0]=9;$val[1]=10;
var_dump($arr,$val);

输出:array(3) {
  [0]=>
  int(2)
  [1]=>
  int(4)
  [2]=>
  &array(2) {
    [0]=>
    int(9)
    [1]=>
    int(10)
  }
}array(2) {
  [0]=>
  int(9)
  [1]=>
  int(10)
}

Since $arr ​​as &$val, loop to the third element,

val. Although it is reassigned to an empty array, subsequent modifications will still affect

val is a reference, and subsequent modifications will affect it. , unless unset($val) is added.

Related recommendations:

Scope and block-level scope in Javascript

Is PHP function scope or block-level scope?

JavaScript anonymous function imitating block-level scope_javascript skills

The above is the detailed content of Detailed explanation of PHP{} block-level scope. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn