首页 > 代码库 > PHP基础知识(一)
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 integervar_dump($a == 5); // compare value; return truevar_dump($a == ‘5‘); // compare value (ignore type); return truevar_dump($a === 5); // compare type/value (integer vs. integer); return truevar_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.
<?phpfunction 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 implementedfunction 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 的负担。
PHP基础知识(一)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。