⊗ppOpTrAMt 83 of 107 menu

Abstract Methods of Traits in OOP in PHP

In traits, some methods can be declared abstract. In this case, the class using this trait will be obliged to implement such a method. At the same time, abstract methods of a trait cannot be private.

Let's look at an example. Suppose we have the following trait:

<?php trait TestTrait { public function method1() { return 1; } abstract public function method2(); } ?>

Suppose our trait is used by the Test class. The presence of an abstract method in the trait will obligate the programmer to implement it in the class, otherwise there will be a PHP error.

Let's create the Test class along with the method2 method:

<?php class Test { use TestTrait; // using the trait // Implementing the abstract method: public function method2() { return 2; } } new Test; ?>

Copy the code of my TestTrait trait and the code of my Test class. Remove the method2 method from the class. Make sure that the absence of its implementation leads to a PHP error.

byenru