Explanation
After writing Java for a period of time, I am particularly not used to PHP’s own weak typing method. I always feel uneasy when writing code, especially PHP itself is a weakly typed language, so when coding, there are often no code prompts.
A general example
class Data { public $name; public $gender; public $age; public function __construct($name,$gender,$age) { $this->name = $name; $this->gender = $gender; $this->age = $age; } } class Test { public function run() { $data = [ new Data('张三','男',18), new Data('李四','男',14), new Data('王五','男',17), new Data('大姨妈','女',23), ]; } private function eachData($data) { foreach($data as $item) { echo $item->name.'=>'.$item->gender.'=>'.$item->age."\n"; } } } (new Test)->run();
Judging from the above example, generally speaking, there is no problem. However, when writing the code
cho $item->name.'=>'.$item->sex.'=>'.$item->age."\n";
, when calling There is no automatic prompt for attributes, so when the amount of data is large, you need to scroll up and copy or write it down, which reduces the coding speed, and sometimes you are not sure what to write, and you are afraid of making mistakes.
The following is a complete example I wrote using comments and PHP features:
class Data { public $name; public $gender; public $age; public function __construct($name,$gender,$age) { $this->name = $name; $this->sex = $gender; $this->age = $age; } } class Test { public function run() { $data = [ new Data('张三','男',18), new Data('李四','男',14), new Data('王五','男',17), new Data('大姨妈','女',23), ]; } /** * 遍历输出数据 * @param array $data */ private function eachData($data) { foreach($data as $item) { if($item instanceof Data) { echo $item->name.'=>'.$item->gender.'=>'.$item->age."\n"; } } } } (new Test)->run();
The main thing here is to add an if judgment to determine whether the data type is a specific instance of Data ;
In this place, PHPstorm will automatically prompt when calling the $item attribute based on this judgment, which is very convenient.
Thinking
Some thoughts I got from here is that we can better consider the rigor when writing the program. From the above example, we can do it this way, and add Some error handling mechanisms can better ensure the security and integrity of data, not just the convenience of editor prompts.
When you do code inspection and tracking later, it will be a very convenient thing, and the business logic will be clearer.