{"id":118,"date":"2023-09-18T13:57:47","date_gmt":"2023-09-18T11:57:47","guid":{"rendered":"https:\/\/extendsclass.com\/blog\/?p=118"},"modified":"2023-05-26T08:49:44","modified_gmt":"2023-05-26T06:49:44","slug":"using-traits-in-php","status":"publish","type":"post","link":"https:\/\/extendsclass.com\/blog\/using-traits-in-php","title":{"rendered":"Using Traits in PHP"},"content":{"rendered":"\n<p>Let&#8217;s explore PHP traits, their usage, and how they differ from interfaces and abstract classes.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_47_1 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"ez-toc-toggle-icon-1\"><label for=\"item-69dab01287a9d\" aria-label=\"Table of Content\"><span style=\"display: flex;align-items: center;width: 35px;height: 30px;justify-content: center;direction:ltr;\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/label><input  type=\"checkbox\" id=\"item-69dab01287a9d\"><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/extendsclass.com\/blog\/using-traits-in-php\/#What_are_Traits\" title=\"What are Traits?\">What are Traits?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/extendsclass.com\/blog\/using-traits-in-php\/#What_can_Traits_contain\" title=\"What can Traits contain?\">What can Traits contain?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/extendsclass.com\/blog\/using-traits-in-php\/#When_to_use_a_trait\" title=\"When to use a trait?\">When to use a trait?<\/a><ul class='ez-toc-list-level-3'><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/extendsclass.com\/blog\/using-traits-in-php\/#Traits_vs_Interfaces\" title=\"Traits vs Interfaces\">Traits vs Interfaces<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/extendsclass.com\/blog\/using-traits-in-php\/#Traits_vs_Abstract_Classes\" title=\"Traits vs Abstract Classes\">Traits vs Abstract Classes<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/extendsclass.com\/blog\/using-traits-in-php\/#Conflict_Resolution\" title=\"Conflict Resolution\">Conflict Resolution<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_are_Traits\"><\/span>What are Traits?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>A&nbsp;<strong>trait<\/strong>&nbsp;lets you&nbsp;<strong>reuse code<\/strong>. A Trait is similar to a class, but it is not possible to instantiate it. It enables horizontal composition of behavior. Traits are used to define methods that can be utilized in multiple classes.<\/p>\n\n\n\n<p>Traits are declared with the&nbsp;<code>trait<\/code>&nbsp;keyword:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>trait GreetingTrait {\n    public function sayGoodbye() {\n        echo \"Goodbye! \";\n    }\n}\n\nclass MyClass {\n    use GreetingTrait;\n}\n\n$obj = new MyClass();\n$obj-&gt;sayGoodbye(); \/\/ Output: Goodbye!<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/extendsclass.com\/php-bin\/85b009b\" title=\"\">Try it yourself<\/a><\/p>\n\n\n\n<p>Traits are a mechanism for code reuse in single inheritance languages, which means that a child class can inherit from only one parent class. However, if a class needs to inherit multiple behaviors, this limitation can be overcome using traits.<\/p>\n\n\n\n<p>Another possible use:Traits can also be used to split a large php file. Ideally in this case, several classes should be recreated, but while waiting for a major rework, the Traits can help with readability (It&#8217;s not pleasant to have to scroll like crazy\u2026).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_can_Traits_contain\"><\/span>What can Traits contain?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>PHP traits can contain many of the elements of a PHP class:<\/p>\n\n\n\n<ul>\n<li>Properties and methods  with visibility operators (public, protected, private)<\/li>\n\n\n\n<li>Static properties and methods<\/li>\n\n\n\n<li>Class operators, such as&nbsp;<em>parent::<\/em>,&nbsp;<em>self::<\/em>&nbsp;and&nbsp;<em>$this<\/em><\/li>\n\n\n\n<li>Abstract methods<\/li>\n\n\n\n<li>Constants properties<\/li>\n\n\n\n<li>Traits!<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"When_to_use_a_trait\"><\/span>When to use a trait?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Traits have similarities with interfaces and with abstract classes.  Let&#8217;s see the differences.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Traits_vs_Interfaces\"><\/span><strong>Traits vs Interfaces<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Interfaces allow multiple classes to share the same methods, but they are limited to abstract methods and do not support code reuse. On the contrary, traits offer fully implemented methods, properties, and class operators, allowing classes to reuse trait code without duplication.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Traits_vs_Abstract_Classes\"><\/span>Traits vs Abstract Classes<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Both traits and abstract classes can include abstract or fully implemented methods.<\/p>\n\n\n\n<p>Extending an abstract class is required to access its methods in another class.<\/p>\n\n\n\n<p>While establishing an inheritance relationship with an abstract class is necessary to utilize its methods, it may not always be preferable.<\/p>\n\n\n\n<p>PHP lacks support for multiple inheritance, which restricts the creation of different combinations through separate abstract classes.<\/p>\n\n\n\n<p>However, traits offer a solution by enabling the simultaneous usage of multiple traits within the same class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conflict_Resolution\"><\/span>Conflict Resolution<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>PHP traits support&nbsp;<strong>aliasing<\/strong>. You can alias a trait\u2019s method to change its name and even change the visibility!<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>trait GreetingTrait {\n    public function sayGoodbye() {\n        echo \"Goodbye! \";\n    }\n}\n\nclass MyClass {\n    use GreetingTrait {\n        sayGoodbye as farewell;\n    }\n}\n\n$obj = new MyClass();\n$obj-&gt;farewell();  \/\/ Output: Goodbye!<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/extendsclass.com\/php-bin\/a8a6d16\" title=\"\">Try it yourself<\/a><\/p>\n\n\n\n<p>If two Traits have  a method with the same name, then there is a conflict and a fatal error is produced, if the conflict is not explicitly resolved.<\/p>\n\n\n\n<p>You must explicitly&nbsp;<strong>solve the conflict<\/strong> the&nbsp;<code>insteadof<\/code>&nbsp;operator, which allows to choose exactly one of the conflicting methods .<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>trait GreetingTrait {\n    public function sayGoodbye() {\n        echo \"Goodbye! \";\n    }\n}\n\ntrait SalutationTrait {\n    public function sayGoodbye() {\n        echo \"See you later! \";\n    }\n}\n\nclass MyClass {\n    use GreetingTrait, SalutationTrait {\n        SalutationTrait::sayGoodbye insteadof GreetingTrait;\n        GreetingTrait::sayGoodbye as farewell;\n    }\n}\n\n$obj = new MyClass();\n$obj-&gt;sayGoodbye();  \/\/ Output: See you later!\n$obj-&gt;farewell();    \/\/ Output: Goodbye!\n<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-center\"><a href=\"https:\/\/extendsclass.com\/php-bin\/e1433c2\" title=\"\">Try it yourself<\/a><\/p>\n\n\n\n<p class=\"has-text-align-center\">Learn more <a href=\"https:\/\/www.php.net\/manual\/en\/language.oop5.traits.php\" title=\"\">PHP: Traits<\/a><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>What PHP Traits are and how to use them.<\/p>\n","protected":false},"author":1,"featured_media":124,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_sitemap_exclude":false,"_sitemap_priority":"","_sitemap_frequency":""},"categories":[2],"tags":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/posts\/118"}],"collection":[{"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/comments?post=118"}],"version-history":[{"count":21,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/posts\/118\/revisions"}],"predecessor-version":[{"id":120,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/posts\/118\/revisions\/120"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/media\/124"}],"wp:attachment":[{"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/media?parent=118"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/categories?post=118"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/tags?post=118"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}