How can Traits be used in PHP to share methods between classes, and what are their advantages compared to inheritance?
Traits in PHP can be used to share methods between classes by allowing you to define methods in a trait and then include that trait in multiple classes. This helps in avoiding code duplication and promotes code reusability. Traits are advantageous compared to inheritance as they allow for code reuse in classes that may not be directly related through a parent-child relationship.
<?php
trait Logging {
public function log($message) {
echo $message;
}
}
class User {
use Logging;
public function createUser() {
$this->log('User created successfully');
}
}
class Product {
use Logging;
public function createProduct() {
$this->log('Product created successfully');
}
}
$user = new User();
$user->createUser();
$product = new Product();
$product->createProduct();