Constructors with a return value can be unproductive in PHP

Production RiskSoftware ResiliencyCode Reliability

Constructors with a return value can be unproductive in PHP

This code insight counts a violation each time the script has a constructor with a return value

” <?php
class foo {

function foo(){
$error = ”; // is set when something goes wrong
// things that can go wrong
return $error;
}
}

$foo = new foo();

?>”

Remedy –

“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.”

” <?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();

?>”

5362

Why you should care

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.

Business Impacts

Production Risk

CAST recommendations

References

https://www.tutorialspoint.com/sql/sql-transactions.htm

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.

See featuresHow it works