Câu hỏi phỏng vấn PHP
Câu hỏi

Explain the Order of Pre...

Câu trả lời

Order of Precedence for Traits in PHP

In PHP, when a class uses multiple traits, the order in which the traits are listed in the use statement determines the precedence of the methods. If two traits define a method with the same name, the trait listed last in the use statement takes precedence.

Here's the order of precedence for traits in PHP:

  1. Methods from the current class take precedence over trait methods.
  2. Methods from the first used trait take precedence over methods from the second used trait, and so on.
  3. If two traits use the same trait, the trait listed last in the use statement takes precedence.
  4. If a trait defines a method and the current class defines a method with the same name, the class method takes precedence.

Here's an example to illustrate the order of precedence:

php Copy
trait Trait1 {
    public function sayHello() {
        echo "Hello from Trait1";
    }
}

trait Trait2 {
    public function sayHello() {
        echo "Hello from Trait2";
    }
}

class MyClass {
    use Trait1, Trait2;

 ...
senior

senior

Gợi ý câu hỏi phỏng vấn

senior

How to turn errors into exceptions in PHP?

junior

Is there a difference between isset and !empty ?

entry

What does $GLOBALS mean?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào