How To Use PHP OOP - Traits Example ?

PHP 8 , PHP

Nicesnippets

298

17-07-2021


How To Use PHP OOP - Traits Example ?

Hi guys,

Today i will explained How To Use OOP - traits in php. This example is so easy to use in php.

Php is a only supported to the single inheritance: a child class can inherit only from one single parent method.

So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.

Traits is used to declare methods to used in multiple classes. Traits can have methods and abstract methods that can be use in multiple classes, and methods can have any access specifier (public, private, or protected).

So let's start to the example.

index.php


<!DOCTYPE html>

<html>

<body>

<?php

trait traitMethod {

public function message() {

echo "How are you.This is trait method. ";

}

}

class Welcome {

use traitMethod;

}

$obj = new Welcome();

$obj->message();

?>

</body>

</html>

Output

How are you.This is trait method.

Now you can check your own.

I hope it can help you...


Recommended Posts