Hello. While doing some code review in a PHP 7.4 project, I found that there is no error or warning for chained function/method calls where return values could be null and cause an error. Could an error be implemented for these cases since it should be handled properly in code? If it were PHP 8, a potential solution would be optional chaining for example. Please see this test case: https://onlinephp.io?s=jZI9b8MgEIZ3S_4PDAx48NLVrTN0brt0jxx0iakcbJkjUVXlvxf8gbFwhJngPl7ueXWvh67u0iRNZHUF1VUcyMfvNygsbJA3lVIm8HX6AY4vafKXJsScrhe3CoEo7IW8EGqbh4YhqU-N4OSsJUfRSnI88laaSs2R-Q3ZWD5J2kOxFiovbZK8OVWbeTwTvwB-mjIWivWAupe-5qL1COECtoPDJvQ6X3dBPgVzMoZO6qaJwSnAqYFtDTOp7PpuhRBzdP40ZuqG5spZu0fv9h6YO-Msc-1yNmyLwvvsMXQ0825AizNhdF7KtXpe-nYNr3EdM1_AHuB1u1rpaRLfN-oNLeHuXGJZMSSdnybsSlyQLaYUk5rfkJcjXvEP&v=7.4.33
<?php namespace MyTest; class MyObject2 { private string $name; public function __construct(string $name) { $this->name = $name; } public function getName() { return $this->name; } } class MyObject { private ?MyObject2 $myObject2; public function __construct() { $this->myObject2 = null; } public function setObject2(MyObject2 $myObject2 = null) { $this->myObject2 = $myObject2; } public function getObject2() { return $this->myObject2; } } class MyTestClass { private MyObject $myObject; public function __construct(MyObject $myObject) { $this->myObject = $myObject; } public function test() { if ($name = $this->myObject->getObject2()->getName()) { echo $name; } } } $myObject = new MyObject(); $myTestClassObj = new MyTestClass($myObject); $myTestClassObj->test();
In this code, an error occurs for $this->myObject->getObject2()->getName() at runtime because getObject2() returns null as it may by design. But we weren't warned by code analysis of this possibility despite not having a check before it in the same condition or block to ensure it is not null like if ($this->myObject->getObject2() && ...).
$this->myObject->getObject2()->getName()
getObject2()
if ($this->myObject->getObject2() && ...)
Thank you!
Thank you for the suggestion.
We used to report this but - it is so frequent case in most PHP code bases that we had to turn this off.
We may make this as an optional setting though.