PHP Traits - Multiple Choice Questions

PHP Traits - Multiple Choice Questions


A PHP trait is a partial class implementation (i.e. constants, properties and methods) that can be mixed into one or more existing PHP classes. Traits work double duty: they say what a class can do (like an interface), and they provide a modular implementation (like a class). [Modern PHP: New Features and Good Practices By Josh Lockhart]

Try below quiz questions and check your knowledge on PHP Traits.

1) We use . . . . . keyword to declare a trait and . . . . keyword is used in order to include it in a class.

A) Declare, Use
B) Initiate, Include
C) Trait, Use
D) none of above

2)

We can use above trait in any of the class as:
A)
 class Welcomeclass{
 use Trait Welcome;
}
B)
 class Welcomeclass{
 use Welcome:
}
C)
 class Welcomeclass{
 use Welcome;
}
D)
 class Welcomeclass{
 use=> Welcome;
}

3) Methods declared in a class using a trait take precedence over methods declared in the trait. However, methods in a trait will override methods inherited by a class.

A) True
B) False

4) Both namespaces and traits are imported with the 'use' keyword. Where they are imported is different. We import namespaces, classes, interfaces, functions and constants . . . . . of a class definition. We import traits . . . . . a class definition.

A) inside, outside
B) outside, inside

5) Traits do not encourage code reuse.

A) True
B) False

6) The static members in traits are linked to whichever . . . . uses them, rather than the trait itself.

A) class
B) method
C) properties
D) none of above

7) There can be situations where a class uses two traits with the same method and this may cause the code to throw an error. To avoid errors like this, you can use the operator . . . . . .

A) identity
B) union
C) insteadof
D) xor

8) Traits can be further composed of other traits, even supporting the . . . . . . .

A) constants
B) abstract members
C) static members
D) none of above

9) Multiple Interfaces can be used in the same class, and but not multiple traits.

A) True
B) False

10) Unlike abstract class and an interface, traits can be instantiated.

A) True
B) False

Answers