dongshao5573 2018-01-26 17:00
浏览 117

在PHP中的类内部使用时,traits中的静态变量如何不会丢失它的值?

How don't the static properties in traits lose its value when used by classes Although Traits are language assisted Copy/paste? let's consider the following example,

     trait Test{
    public static $var = 1;

   public static  function increment(){
        self::$var ++;
        var_dump(self::$var);
    }
}


Test::increment();//2



class Test2{

    use Test;

}

var_dump(Test2::$var);//2
Test2::increment();//3

This behaviour is correct in inheritance where the child extends the parent, so the child uses the parent static variables, but according to traits where copy and paste are applied, how does this work and correct?


This is an update to add another reason to the confusion I have, if the static values are reserved to specific contexts like specific class or function, so how do I able to use updated values of static properties from a different context ( the new class). I mean, if the context of trait Test is called for example Context1, and the class Test2 context is called Context2, how do I access the reserved values of the first context in another context? this is against the contexts approach we understand.


Update 3: all of this confusion depends on if the use keyword is importing the trait members in class or copy/paste?

  • 写回答

2条回答 默认 最新

  • dongyinzheng6572 2018-01-26 17:29
    关注

    From Trait Documentation

    A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

    You can't instantiate a Trait on it's own, and you can't define the properties that the Trait is using as they will conflict, that is because a Trait "adds" this functionality to a Class you're attaching it to.

    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码