⊗ppOpTrMT 78 of 107 menu

Multiple Traits in OOP in PHP

A class can use not one, but several traits. This is where their advantage over inheritance manifests itself. The traits needed for use in a class can be listed separated by commas after the keyword use.

Let's look at an example. Suppose we have two traits. First:

<?php trait Helper1 { private $name; public function getName() { return $this->name; } } ?>

Second:

<?php trait Helper2 { private $age; public function getAge() { return $this->age; } } ?>

Let's use our traits in a class:

<?php class User { use Helper1, Helper2; // connect traits public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } ?>

Create 3 traits named Trait1, Trait2 and Trait3. Let the first trait have a method method1 returning 1, the second trait - a method method2, returning 2, and the third trait - a method method3, returning 3. Let all these methods be private.

Create a class Test that uses all three traits we created. Create a public method getSum in this class, returning the sum of the results of the methods of the connected traits.

byenru