对于允许在非静态上下文中修改静态变量的语言,这是一种很好的做法吗?

时间:2014-09-03 02:01:52

标签: java php oop

在面向对象编程方面,允许在非静态上下文中修改静态变量是一种很好的做法吗?

在Java中,允许在非静态上下文中访问静态变量。例如,在以下代码中,interest类变量仍然可以在MyClass instance1MyClass 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

0 个答案:

没有答案