Home > Backend Development > PHP Tutorial > Common mistakes in PHP

Common mistakes in PHP

小云云
Release: 2023-03-22 16:56:01
Original
1251 people have browsed it

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);

}
Copy after login

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;);

}
Copy after login

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;];
Copy after login

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
Copy after login

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』
Copy after login

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template