美文网首页
Unlike inheritance; if a trait h

Unlike inheritance; if a trait h

作者: 张霸天 | 来源:发表于2017-03-24 17:47 被阅读0次

    Unlike inheritance; if a trait has static properties, each class using that trait has independent instances of those properties.

    Example using parent class:

    
    <?php
    class TestClass {
        public static $_bar;
    }
    class Foo1 extends TestClass { }
    class Foo2 extends TestClass { }
    Foo1::$_bar = 'Hello';
    Foo2::$_bar = 'World';
    echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: World World
    ?>
    
    Example using trait:
    <?php
    trait TestTrait {
        public static $_bar;
    }
    class Foo1 {
        use TestTrait;
    }
    class Foo2 {
        use TestTrait;
    }
    Foo1::$_bar = 'Hello';
    Foo2::$_bar = 'World';
    echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: Hello World
    ?>
    
    

    相关文章

      网友评论

          本文标题:Unlike inheritance; if a trait h

          本文链接:https://www.haomeiwen.com/subject/cmvfottx.html