douwei2713 2016-02-11 08:26
浏览 43

PHP静态属性行为

I'm trying to understand static property behavior in an abstract class.this is an example code retrieved from php object patterns and practice book (chapter 11-decorative pattern) :

abstract class Expression {

   private static $keycount=0;

   private $key;

   function getKey() {
    if ( ! isset( $this->key ) ) {
        self::$keycount++;
        $this->key=self::$keycount;
      }

    return $this->key;
   }
}

a number of sub classes are extended from this abstract class and then getKey() method will be called at instantiating time.each one check its own $key property and if its null ,then increase $keycount by one and assign it to $key property .
as i understand $keycount save its last value regardless of which subclass its running on . i mean it is in the context of abstract class NOT the context of sub classes. if it was dependent to its subclass then it would be reset to 0 in each subclass.can anyone provide me more insight into this ?

  • 写回答

1条回答 默认 最新

  • dongtai419309 2016-02-12 23:30
    关注

    It looks like you answer your own question.

    as i understand $keycount save its last value regardless of which subclass its running on

    Yes, it works this way. The $keycount is shared between all subclasses. Here is a simple test to check this behavior:

    <?php
    abstract class Expression {
    
       private static $keycount=0;
    
       private $key;
    
       function getKey() {
        if ( ! isset( $this->key ) ) {
            self::$keycount++;
            $this->key=self::$keycount;
          }
    
        return $this->key;
       }
    }
    
    class ChildOne extends Expression {
    }
    
    class ChildTwo extends Expression {
    }
    
    $one = new ChildOne();
    print 'One get key: ' . $one->getKey().PHP_EOL;
    print 'One get key: ' . $one->getKey().PHP_EOL;
    $oneMore = new ChildOne();
    print 'One more get key: ' . $oneMore->getKey().PHP_EOL;
    print 'One more get key: ' . $oneMore->getKey().PHP_EOL;
    $two = new ChildTwo();
    print 'Two get key: ' . $two->getKey().PHP_EOL;
    print 'Two get key: ' . $two->getKey().PHP_EOL;
    

    Output:

    One get key: 1
    One get key: 1
    One more get key: 2
    One more get key: 2
    Two get key: 3
    Two get key: 3
    
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler