Skip to content

Instantly share code, notes, and snippets.

@prashantdsala
Created March 21, 2023 09:44
Show Gist options
  • Save prashantdsala/a5ac69de1a6e3862e8f05a35b5d34cde to your computer and use it in GitHub Desktop.
Save prashantdsala/a5ac69de1a6e3862e8f05a35b5d34cde to your computer and use it in GitHub Desktop.
Traits example in PHP
<?php
// In this example, we define a trait called Greetings which contains two methods: sayHello() and sayGoodbye().
// We then define a class called Person and use the Greetings trait within it using the use keyword.
// This allows the Person class to have access to the methods defined in the Greetings trait.
// We create an instance of the Person class and call the sayHello() and sayGoodbye() methods,
// which output "Hello!" and "Goodbye!", respectively.
trait Greetings {
public function sayHello() {
echo "Hello!";
}
public function sayGoodbye() {
echo "Goodbye!";
}
}
class Person {
use Greetings;
}
$person = new Person();
$person->sayHello(); // Output: Hello!
$person->sayGoodbye(); // Output: Goodbye!
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment