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

Detailed explanation of PHP{} block-level scope

小云云
Release: 2023-03-21 06:56:01
Original
2610 people have browsed it

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
Copy after login

{}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;
Copy after login
for ($i = 0; $i < 10; $i++) {    for ($j = 0; $j < 10; $j++) {        $k = 777;
    }
}
var_dump($j);//输出10var_dump($k);//输出777
Copy after login
$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)
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template