use Keyword for Traits Inside Classes
-
Rule: The
usekeyword to implement traits MUST be declared on the next line after the opening brace ({) of the class. -
Reason: This ensures clarity by keeping the trait declarations visually separated from the rest of the class body. It helps in distinguishing between the class definition and the traits being used by the class.
Example (Correct):
class MyClass
{
use MyTrait;
// Other class members
}
Example (Incorrect):
class MyClass { use MyTrait; }
Empty Line After use Keyword
-
Rule: There MUST be an empty line after the
usekeyword when declaring traits in the class. -
Reason: Adding an empty line after the
usestatement improves readability by visually separating the trait declarations from the rest of the class code.
Example (Correct):
class MyClass
{
use MyTrait;
public $var;
//...
}
Example (Incorrect):
class MyClass
{
use MyTrait;
public $var;
//...
}
insteadof and as Operators on New Lines
-
Rule: When using the
insteadofandasoperators for trait conflict resolution, they MUST be placed on new lines. -
Reason: Each operator should be placed on its own line to enhance readability and make the conflict resolution mechanism more transparent. This also prevents cluttering the code and keeps it clear which methods are being aliased or overridden.
Example (Correct):
class MyClass
{
use MyTrait1 {
MyTrait1::methodName insteadof MyTrait2;
MyTrait2::methodName as newMethodName;
}
}
Example (Incorrect):
class MyClass
{
use MyTrait1 {
MyTrait1::methodName insteadof MyTrait2; MyTrait2::methodName as newMethodName;
}
}
Summary:
-
usekeyword for traits should be declared on the next line after the class's opening brace. -
There must be an empty line after the
usestatement. -
When using the
insteadofandasoperators for trait conflict resolution, they MUST be placed on separate lines.