In what situations would it be more appropriate to use traits instead of class inheritance in PHP?
Traits are more appropriate than class inheritance in PHP when you want to share methods among classes that are not related by a common hierarchy. Traits allow for code reuse without creating a tight coupling between classes, making it easier to maintain and extend functionality.
trait Logging {
public function log($message) {
echo $message;
}
}
class User {
use Logging;
public function __construct() {
$this->log('User created');
}
}
class Product {
use Logging;
public function __construct() {
$this->log('Product created');
}
}
$user = new User(); // Output: User created
$product = new Product(); // Output: Product created
Keywords
Related Questions
- What are the potential pitfalls of using mysqli_query without proper error handling in PHP code?
- How can PHP be used to limit the number of guestbook entries shown per page, for example, displaying only 10 entries at a time?
- Is there a more efficient way to achieve the desired outcome without using a PNG file to call a PHP file?