note 125032 added to language.oop5.traits
| From: | Anonymous@php.net | Date: | Wed, 20 May 2020 19:32:21 +0000 |
| Subject: | note 125032 added to language.oop5.traits | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214660@lists.php.net to get a copy of this message | ||
Trait, utility, or inheritance?
You can view a trait as a collection of utility functions with access to $this, without first having
to declare (or think about) which classes $this could belong to.
Anytime you want to carve out (a.k.a factor out, "cut & paste") a section of code that
you want to use in other classes too, and you need $this, then you should put the code in a trait
function.
Trait functions can also use $this to share data among each other.
If you don't need access to $this, you could carve out the code into a utility function or a
separate utility class outside your original class. To share data among functions of a utility class
you will have to pass around a utility object. Since a trait is more intimately tied in through
$this, there is nothing you need to pass around.
Common functionality can also be factored out into a parent class. Such a parent class could sit in
between a base class from a library and several child classes that you write. However, all your
classes that use the common functionality must then inherit from the "in between" parent.
This means they cannot be children from any other class. If the common functionality is general
enough to be used with other base classes, you will end up having to duplicate ("copy &
paste") the code into several "in between" classes. With a trait you won't have
to, which in most cases makes it easier to update and improve the common functionality.
----
Server IP: 45.112.84.4
Probable Submitter: 103.51.166.36 (proxied: 2001:569:72cc:6100:e58a:e762:964b:96ac)
----
Manual Page -- http://php.net/manual/en/language.oop5.traits.php
Edit -- https://master.php.net/note/edit/125032
Del: integrated -- https://master.php.net/note/delete/125032/integrated
Del: useless -- https://master.php.net/note/delete/125032/useless
Del: bad code -- https://master.php.net/note/delete/125032/bad+code
Del: spam -- https://master.php.net/note/delete/125032/spam
Del: non-english -- https://master.php.net/note/delete/125032/non-english
Del: in docs -- https://master.php.net/note/delete/125032/in+docs
Del: other reasons-- https://master.php.net/note/delete/125032
Reject -- https://master.php.net/note/reject/125032
Search -- https://master.php.net/manage/user-notes.php