CRITICAL
Rule Definition
In PHP a constructor is the function that is called when an object is created and can be used to initialize object-variables. Using a return-value in a constructor is probably used to generate an error when something goes wrong during initialization. The return value from an object will be ignored and the result will always be the object itself. In this situation, the returned value of the constructor is a corrupt object which will be re-used in the source code and which could produce unexpected results.
Remediation
Review the source code and if the issue is related to the management of the errors you can always adopt the approach below:
If something goes wrong in the constructor you can either:
- Throw an exception (PHP5 only)
- Put this functionality in a separate function and call it. This function can then either return the object or an error.
Violation Code Sample
<?php
class foo {
function foo(){
$error = ''; // is set when something goes wrong
// things that can go wrong
return $error;
}
}
$foo = new foo();
?>
Fixed Code Sample
<?php
class foo {
function foo(){
// things that can not go wrong
}
function createFoo(){
// is set to something else
// when something goes wrong
$error = new foo();
// things that can go wrong
return $error;
}
}
$foo = foo::createFoo();
?>
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.