herozw
V2EX  ›  PHP

PHP class 中静态属性和普通属性,分别在什么时候用到?

  •  
  •   herozw · Oct 9, 2017 · 3285 views
    This topic created in 3165 days ago, the information mentioned may be changed or developed.

    知道 static 属性在一次声明后,会存在于内存,效率较高。 如果类中要定义一个开始时间,用静态属性还是用普通属性。

    9 replies    2017-10-10 21:30:46 +08:00
    crystom
        1
    crystom  
       Oct 9, 2017
    这点时间对代码效率几乎没有影响
    zjsxwc
        2
    zjsxwc  
       Oct 9, 2017
    想怎么用就怎么用呗, 看看 laravel 的 facade,虽然你用起来是类静态属性,但实际背后是实例对象的普通属性。
    GOOD21
        3
    GOOD21  
       Oct 9, 2017
    最优的话当时是静态的好了。
    GOOD21
        4
    GOOD21  
       Oct 9, 2017
    如果用普通的,假如你的 php 进程要执行 2 秒钟,那么这个开始时间是会变的。
    Sikoay
        5
    Sikoay  
       Oct 9, 2017 via Android
    不要乱用 static 变量,基本原则,就算要用,一般我都是用的都是 final static 或者是 get&set 看具体场景吧
    Sikoay
        6
    Sikoay  
       Oct 9, 2017 via Android
    不然程序中多个地方访问同一个 static 变量,不小心修改了就 GG 了,以后出现了 bug 很难排查
    hantsy
        7
    hantsy  
       Oct 10, 2017
    static 最好定义全局不变(+final 整个应用范围只读,比如一些默认参数)或全局共享(可变)的属性。这是 OOP 语言都有的特性。
    jfcherng
        8
    jfcherng  
       Oct 10, 2017
    @hantsy final 只能用在 class 和 method 上吧?
    hantsy
        9
    hantsy  
       Oct 10, 2017
    @jfcherng PHP 现在我好久没写了,我的表述在 Java 中应该不成问题的,https://github.com/hantsy/angularjs-springmvc-sample-boot/blob/master/src/main/java/com/hantsylabs/restexample/springmvc/ApiErrors.java
    这些用法在 OOP 语言都是差不多的。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3288 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 57ms · UTC 13:06 · PVG 21:06 · LAX 06:06 · JFK 09:06
    ♥ Do have faith in what you're doing.