rspec/rules/S5911/php/rule.adoc

47 lines
1.1 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
When specifying the class of objects in a catch clause it is important to make sure that the class exists.
Since no PHP error will be raised if the class does not exist, this can lead to difficult to debug problems as the catch clause will have no effect and the reason might not be obvious.
This mistake often occurs when being in a namespace and catching PHP built-in exception classes without escaping to the global namespace or importing the classes.
This rule raises an issue when, being in a namespace, an undefined class belonging to that namespace is caught.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
namespace Foo\Bar;
try {
doSomething();
} catch (Exception $e) { // Noncompliant - Exception will never be caught because the class Exception does not exist in the namespace
echo $e->message;
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
namespace Foo\Bar;
try {
doSomething();
} catch (\Exception $e) { // Compliant used by global namespace
echo $e->message;
}
// or
namespace Foo\Bar;
use Exception;
try {
doSomething();
} catch (Exception $e) { // Compliant imported by use statement
echo $e->message;
}
----