Home  >  Article  >  Backend Development  >  Common mistakes in PHP

Common mistakes in PHP

小云云
小云云Original
2018-03-29 15:34:521182browse

This article mainly shares with you the common mistakes in PHP, which are summarized when using PHP in daily life. I hope it can help everyone.

1 Quoted question

<?php$arr = range(1,3);foreach ($arr as &$v){
}


print_r($arr);foreach ($arr as $v){
    print_r($arr);

}

Common mistakes in PHP

2 Detecting whether a variable is set

<?php$data = array();//$data[&#39;name&#39;]  = 0;//$data[&#39;name&#39;]  = null;$data[&#39;name&#39;] = false;if (isset($data[&#39;name&#39;])) {
    var_dump(&#39;not set name&#39;);
} else {
    var_dump(&#39;already set name&#39;);

}if (($data[&#39;name&#39;])) {
    var_dump(&#39;data-name 存在&#39;);
} else {
    var_dump(&#39;data-name 不存在&#39;);

}if (array_key_exists(&#39;name&#39;, $data)) {
    var_dump(&#39;key name 存在于array中&#39;);
} else {
    var_dump(&#39;key name 不存在于array中&#39;);

}

Three values, three ways to determine whether a variable exists The results are:
Common mistakes in PHP
Common mistakes in PHP

Common mistakes in PHP

3 Directly use the data index returned by the function

<?phpclass Config{
    private $values = [];    public function __construct() {
        // 使用数组对象而不是数组
        // $this->values = new ArrayObject();
    }    public function &getValues() {
        return $this->values;
    }
}$config = new Config();$config->getValues()[&#39;test&#39;] = &#39;test&#39;;echo $config->getValues()[&#39;test&#39;];

If you do not use object to store values, or do not use a reference to turn the result of the function into a reference to the values ​​array, then it may be wrong

Notice: Undefined index: test in /Users/leon/Documents/workspace/test/php7.php on line 20

This will destroy the encapsulation of the object, it is best to write like this

class Config{
    private $values = [];    public function setValue($key, $value) {
        $this->values[$key] = $value;
    }    public function getValue($key) {
        return $this->values[$key];
    }
}$config = new Config();$config->setValue(&#39;testKey&#39;, &#39;testValue&#39;);echo $config->getValue(&#39;testKey&#39;);    // 输出『testValue』

The above is the detailed content of Common mistakes in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn