instructions

After writing Java for a period of time, I am not used to the weak-typed way of PHP itself, and I always feel uneasy when writing code. Especially PHP itself is a weak-typed language, so there is no code prompt in many cases when coding.

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(a) {
        $data = [
            new Data('Joe'.'male'.18),
            new Data('bill'.'male'.14),
            new Data('Cathy'.'male'.17),
            new Data('Period'.'woman'.23)]; }private function eachData($data) {
        foreach($data as $item) {
            echo $item->name.'= >'.$item->gender.'= >'.$item->age."\n"; }}} (new Test)->run();Copy the code

The above examples, in general, there is no problem, but in writing

cho $item->name.'= >'.$item->sex.'= >'.$item->age."\n";Copy the code

This code, when calling the attribute is not automatically prompted, so when the amount of data need to turn up and then copy or write down, reduce the coding speed, and sometimes the heart is not spectrum, afraid of writing wrong.

Here is a complete example I wrote of using comments and their own 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('Joe'.'male',18),
            new Data('bill'.'male',14),
            new Data('Cathy'.'male',17),
            new Data('Period'.'woman', 23)]; } /** * iterate over output data * @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();Copy the code

If the Data type is an instance of Data;

In this case, PHPstorm will automatically prompt you to call the $item attribute based on this judgment, which is very convenient.

thinking

A few things to think about here are that we can write programs with more rigor in mind. From the examples above, this, along with some error-handling mechanisms, can better ensure data security and integrity, not just the convenience of editor prompts.

Later code reviews and traces will also be very convenient, and the business logic will be clearer.