note 119872 added to language.oop5.traits

From: Date: Sat, 10 Sep 2016 18:57:48 +0000
Subject: note 119872 added to language.oop5.traits
Groups: php.notes 
Request: Send a blank email to php-notes+get-206559@lists.php.net to get a copy of this message
A number of the notes make incorrect assertions about trait behaviour because they do not extend the class. So, while "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 ?>" shows a correct example, simply adding <?php require_once('above'); class Foo3 extends Foo2 { } Foo3::$_bar = 'news'; echo Foo1::$_bar . ' ' . Foo2::$_bar . ' ' . Foo3::$_bar; // Prints: Hello news news I think the best conceptual model of an incorporated trait is an advanced insertion of text, or as someone put it "language assisted copy and paste." If Foo1 and Foo2 were defined with $_bar, you would not expect them to share the instance. Similarly, you would expect Foo3 to share with Foo2, and it does. Viewing this way explains away a lot of the 'quirks' that are observed above with final, or subsequently declared private vars, ---- Server IP: 72.52.91.14 Probable Submitter: 45.48.15.67 ---- Manual Page -- http://php.net/manual/en/language.oop5.traits.php Edit -- https://master.php.net/note/edit/119872 Del: integrated -- https://master.php.net/note/delete/119872/integrated Del: useless -- https://master.php.net/note/delete/119872/useless Del: bad code -- https://master.php.net/note/delete/119872/bad+code Del: spam -- https://master.php.net/note/delete/119872/spam Del: non-english -- https://master.php.net/note/delete/119872/non-english Del: in docs -- https://master.php.net/note/delete/119872/in+docs Del: other reasons-- https://master.php.net/note/delete/119872 Reject -- https://master.php.net/note/reject/119872 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#206559) next »