Created
March 21, 2023 09:44
-
-
Save prashantdsala/a5ac69de1a6e3862e8f05a35b5d34cde to your computer and use it in GitHub Desktop.
Traits example in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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