1.2.264. Could Be Protected Class Constant¶
Class constant may use ‘protected’ visibility.
Since PHP 7.1, constants may also have a public/protected/private visibility. This restrict their usage to anywhere, class and children or class.
As a general rule, it is recommended to make constant ‘private’ by default, and to relax this restriction as needed. PHP makes them public by default.
<?php
class foo {
// pre-7.1 style
const PRE_71_CONSTANT = 1;
// post-7.1 style
protected const PROTECTED_CONSTANT = 2;
public const PUBLIC_CONSTANT = 3;
}
class foo2 extends foo {
function bar() {
// PROTECTED_CONSTANT may only be used in its class or its children
echo self::PROTECTED_CONSTANT;
}
}
class foo3 extends foo {
function bar() {
// PROTECTED_CONSTANT may only be used in its class or any of its children
echo self::PROTECTED_CONSTANT;
}
}
// Other constants may be used anywhere
function x($a = foo::PUBLIC_CONSTANT) {
echo $a.' '.foo:PRE_71_CONSTANT;
}
?>
1.2.264.1. Connex PHP features¶
1.2.264.1.1. Suggestions¶
Use protected visibility with the reported constants.
1.2.264.1.2. Specs¶
Short name |
Classes/CouldBeProtectedConstant |
Rulesets |
|
Exakat since |
0.12.11 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Available in |