What is a trait in PHP?
A
A function inside a class
B
A special kind of class that can be instantiated
C
A mechanism for code reuse in single inheritance languages like PHP
Analysis & Theory
Traits are a mechanism for code reuse that allows you to include methods in multiple classes without inheritance.
Which keyword is used to define a trait in PHP?
Analysis & Theory
The `trait` keyword is used to define a trait in PHP.
Which keyword is used to use a trait inside a class?
Analysis & Theory
The `use` keyword is used inside a class to include a trait.
What happens if two traits used in a class have methods with the same name?
B
The method from the last used trait is used
C
You must resolve the conflict manually
Analysis & Theory
Method name conflicts between traits must be resolved manually using `insteadof` and `as` operators.
Can a trait contain properties?
Analysis & Theory
Traits can contain both methods and properties.
Can a class use multiple traits in PHP?
Analysis & Theory
A class can use multiple traits by separating them with commas in the `use` statement.
What is the output?
```
trait Hello {
public function sayHello() {
echo 'Hello';
}
}
class Welcome {
use Hello;
}
$obj = new Welcome();
$obj->sayHello();
```
Analysis & Theory
The output is 'Hello' because the class `Welcome` uses the `Hello` trait which has the method `sayHello()`.
Can traits be used inside other traits?
Analysis & Theory
Yes, traits can use other traits.
What is the primary advantage of using traits?
A
To increase code duplication
B
To avoid object creation
C
To achieve code reuse without traditional inheritance
D
To prevent class instantiation
Analysis & Theory
Traits promote code reuse and solve the problem of single inheritance limitations by allowing multiple trait inclusion.
What is true about traits in PHP?
A
Traits can be instantiated like classes
B
Traits support inheritance
C
Traits cannot have constructors
D
Traits cannot be instantiated and are meant only for including reusable methods
Analysis & Theory
Traits cannot be instantiated. They are designed to group methods and properties to be reused in multiple classes.