在面向对象编程方面,允许在非静态上下文中修改静态变量是一种很好的做法吗?
在Java中,允许在非静态上下文中访问静态变量。例如,在以下代码中,interest
类变量仍然可以在MyClass instance1
和MyClass instance2
中进行修改。
class StaticEx {
public static void main(String[] args) {
MyClass instance1= new MyClass();
MyClass instance2= new MyClass();
// change interest first time
instance1.interest = 100;
System.out.println(MyClass.interest);
System.out.println(instance1.interest);
System.out.println(instance2.interest);
// change interest second time
instance1.interest = 150;
System.out.println(MyClass.interest);
System.out.println(instance1.interest);
System.out.println(instance2.interest);
}
}
MyClass.java
档案:
import java.util.*;
public class MyClass {
public static int interest = 200;
}
输出如下:
100
100
100
150
150
150
在PHP中,不允许这样做:
my_class.php
档案:
<?php
class MyClass {
public static $interest = 200;
public function increase() {
$this->interest = 500;
}
}
$myClass = new MyClass();
$myClass->increase();
echo MyClass::$interest;
输出$: php my_class.php
:
PHP严格标准:在第5行的/home/petwho/Desktop/java/my_class.php中访问静态属性MyClass :: $ interest as non static
严格标准:在第5行的/home/petwho/Desktop/java/my_class.php中访问静态属性MyClass :: $ interest as non static