首页 > 解决方案 > 为什么我们必须在 Java 中的 if 语句之外声明变量

问题描述

在 Java 中,如果我们运行:

public class HelloWorld{

     public static void main(String []args){
         if (true) {
             int test = 1;
         } else {
             int test = 2;
         }
        System.out.println(test);
     }
}

它会抛出:

HelloWorld.java:9: error: cannot find symbol
        System.out.println(test);
                           ^
  symbol:   variable test
  location: class HelloWorld
1 error

但是,在 php 中,如果我们运行:

<?php
        //Enter your code here, enjoy!

if (true) {
    $test = 1;
} else {
    $test = 2;
}

echo $test;

它将打印 1。

我怀疑这是否是因为 Java 是强类型语言而 php 是弱类型语言。有人可以给出更深层次和更低层次的解释吗?

标签: javaphp

解决方案


在 Java 中,变量的可见范围受限于{}

if (true) {
    int test = 1;
} else {
    int test = 2;
}
System.out.println(test);// Will fail to compile

同样重要的是要注意如下所示的死代码:

int test;
if (true) {
    test = 1;
} else {
    test = 2;// Dead code
}
System.out.println(test);

因为块永远不会被执行导致if (true)成为死代码。elsetest = 2


推荐阅读