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); }
2 Detecting whether a variable is set
<?php$data = array();//$data['name'] = 0;//$data['name'] = null;$data['name'] = false;if (isset($data['name'])) { var_dump('not set name'); } else { var_dump('already set name'); }if (($data['name'])) { var_dump('data-name 存在'); } else { var_dump('data-name 不存在'); }if (array_key_exists('name', $data)) { var_dump('key name 存在于array中'); } else { var_dump('key name 不存在于array中'); }
Three values, three ways to determine whether a variable exists The results are:
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()['test'] = 'test';echo $config->getValues()['test'];
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('testKey', 'testValue');echo $config->getValue('testKey'); // 输出『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!