Google News
logo
PHP program to Traits
In the following example of program demonstrating the use of traits in PHP :
Program :
<?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();
?>
Output :
Hello, my name is John
In this example, the `Greeting` trait defines a `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.

When we create an object of the `Person` class and call its `introduce()` method, we see the output "Hello, my name is John".