<?php
// Define a trait with a method
trait Greeting {
public function sayHello() {
echo "Hello, ";
}
}
// Define a class that uses the Greeting trait
class Person {
use Greeting;
private $name;
public function __construct($name) {
$this->name = $name;
}
public function introduce() {
$this->sayHello();
echo "my name is " . $this->name . "\n";
}
}
// Create an object of the Person class and call its methods
$person = new Person("John");
$person->introduce();
?>
Hello, my name is John
sayHello()
` method that simply outputs "Hello, ". The `Person
` class uses the `Greeting
` trait with the `use
` keyword and defines its own `introduce()
` method that calls `sayHello()
` and outputs the person's name.Person
` class and call its `introduce()
` method, we see the output "Hello, my name is John".