⊗ppOpTrAM 80 of 107 menu

Access Modifiers and Traits in OOP in PHP

It should be noted that using traits is not inheritance. With inheritance, private methods and properties are not inherited.

With traits, it's the opposite: in the class using the trait, both public and private methods and properties of the trait will be available.

Let's look at an example. Suppose we have the following trait with a private method:

<?php trait TestTrait { private function method() { return '!!!'; } } ?>

Let's connect our trait to the class:

<?php class Test { use TestTrait; } new Test; ?>

Let's use the trait's private method:

<?php class Test { use TestTrait; // connect the trait public function __construct() { echo $this->method(); // will output '!!!' } } new Test; ?>
byenru