PHP基础知识(一)
The Basics
Comparison operators
Comparison operators are an often overlooked aspect of PHP, which can lead to many unexpected outcomes. One such problem stems from strict comparisons (the comparison of booleans as integers).
<?php $a = 5; // 5 as an integer var_dump($a == 5); // compare value; return true var_dump($a == ‘5‘); // compare value (ignore type); return true var_dump($a === 5); // compare type/value (integer vs. integer); return true var_dump($a === ‘5‘); // compare type/value (integer vs. string); return false /** * Strict comparisons */ if (strpos(‘testing‘, ‘test‘)) { // ‘test‘ is found at position 0, which is interpreted as the boolean ‘false‘ // code... } vs. if (strpos(‘testing‘, ‘test‘) !== false) { // true, as strict comparison was made (0 !== false) // code... }
Conditional statements
If statements
While using ‘if/else’ statements within a function or class, there is a common misconception that ‘else’ must be used in conjunction to declare potential outcomes. However if the outcome is to define the return value, ‘else’ is not necessary as ‘return’ will end the function, causing ‘else’ to become moot.
<?php function test($a) { if ($a) { return true; } else { return false; } } vs. function test($a) { if ($a) { return true; } return false; // else is not necessary }
Switch statements
Switch statements are a great way to avoid typing endless if’s and elseif’s, but there are a few things to be aware of:
- Switch statements only compare values, and not the type (equivalent to ‘==’)
- They Iterate case by case until a match is found. If no match is found, then the default is used (if defined)
- Without a ‘break’, they will continue to implement each case until reaching a break/return
- Within a function, using ‘return’ alleviates the need for ‘break’ as it ends the function
<?php $answer = test(2); // the code from both ‘case 2‘ and ‘case 3‘ will be implemented function test($a) { switch ($a) { case 1: // code... break; // break is used to end the switch statement case 2: // code... // with no break, comparison will continue to ‘case 3‘ case 3: // code... return $result; // within a function, ‘return‘ will end the function default: // code... return $error; } } 如果在一个函数中调用 return 语句,将立即结束此函数的执行并将它的参数作为函数的值返回。return 也会终止 eval() 语句或者脚本文件的执行。 Note: 注意既然 return 是语言结构而不是函数,因此其参数没有必要用括号将其括起来。通常都不用括号,实际上也应该不用,这样可以降低 PHP 的负担。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。