Visibility Declaration
-
Rule: Visibility (e.g.,
public,protected,private) MUST be declared on all properties. -
Reason: Visibility modifiers help clarify how properties can be accessed and modified. Explicit visibility declarations improve code readability and maintainability.
Example:
class MyClass {
public $name;
protected $age;
private $salary;
}
Type Declaration
-
Rule: Type MUST be declared on all properties.
-
Reason: Declaring types for properties helps ensure type safety, prevents errors, and improves code clarity.
Example:
class MyClass {
public string $name;
protected int $age;
private float $salary;
}
Avoid the var Keyword
-
Rule: The
varkeyword MUST NOT be used to declare a property. -
Reason: The
varkeyword is an outdated way of declaring properties, and modern PHP supports explicit visibility modifiers (public,protected,private) and type declarations.
One Property per Statement
-
Rule: There MUST NOT be more than one property declared per statement.
-
Reason: Declaring one property per statement improves code readability and makes it easier to add, modify, or remove properties in the future.
Example (Correct):
class MyClass {
public string $name;
private int $age;
}
Example (Incorrect):
class MyClass {
public string $name, int $age;
}
No Underscore Prefix for Protected/Private Properties
-
Rule: Property names MUST NOT be prefixed with a single underscore to indicate protected or private visibility.
-
Reason: The underscore prefix explicitly has no meaning and can lead to confusion. Visibility should be indicated by the visibility modifier (
public,protected,private), not by a naming convention.
Example (Correct):
class MyClass {
private string $name;
}
Example (Incorrect):
class MyClass {
private string $_name;
}
Space Between Type Declaration and Property Name
-
Rule: There MUST be a space between the type declaration and the property name.
-
Reason: This helps improve readability and aligns with modern PHP conventions.
Example (Correct):
class MyClass {
public string $name;
private int $age;
}
Example (Incorrect):
class MyClass {
publicstring$name;
}
Summary:
-
Visibility MUST be declared on all properties.
-
Type MUST be declared on all properties.
-
varkeyword MUST NOT be used to declare a property. -
There MUST NOT be more than one property declared per statement.
-
Property names MUST NOT be prefixed with a single underscore.
-
There MUST be a space between the type declaration and the property name.