⊗ppOpTrARC 81 of 107 menu

Changing Access Rights to Trait Methods in OOP in PHP

Inside a trait, you can use any access modifier for methods (that is, public, private or protected). However, if necessary, this modifier can be changed to another one in the class itself. To do this, in the body of use after the keyword as, you need to specify the new modifier.

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; } ?>

Let's change the method to public in the class:

<?php class Test { use TestTrait { TestTrait::method as public; } } ?>

Let's test the work of the public method from outside the class:

<?php $test = new Test; echo $test->method(); // will output '!!!' ?>
byenru