1.2.1068. Scalar Or Object Property¶
Property shouldn’t use both object and scalar syntaxes. When a property may be an object, it is recommended to implement the Null Object pattern : instead of checking if the property is scalar, make it always object.
<?php
class x {
public $display = 'echo';
function foo($string) {
if (is_string($this->display)) {
echo $this->string;
} elseif ($this->display instanceof myDisplayInterface) {
$display->display();
} else {
print "Error when displaying\n";
}
}
}
interface myDisplayInterface {
public function display($string); // does the display in its own way
}
class nullDisplay implements myDisplayInterface {
// implements myDisplayInterface but does nothing
public function display($string) {}
}
class x2 {
public $display = null;
public function __construct() {
$this->display = new nullDisplay();
}
function foo($string) {
// Keep the check, as $display is public, and may get wrong values
if ($this->display instanceof myDisplayInterface) {
$display->display();
} else {
print "Error when displaying\n";
}
}
}
// Simple class for echo
class echoDisplay implements myDisplayInterface {
// implements myDisplayInterface but does nothing
public function display($string) {
echo $string;
}
}
?>
See also Null Object Pattern and The Null Object Pattern.
1.2.1068.1. Connex PHP features¶
1.2.1068.1.1. Suggestions¶
Only use one type of syntax with your properties.
1.2.1068.1.2. Specs¶
Short name |
Classes/ScalarOrObjectProperty |
Rulesets |
|
Exakat since |
0.12.3 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Slow (1 hour) |
Precision |
High |
Examples |
|
Available in |