码迷,mamicode.com
首页 > Web开发 > 详细

PHP基础知识(一)

时间:2015-01-24 17:05:45      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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 的负担。

 

 

PHP基础知识(一)

标签:

原文地址:http://www.cnblogs.com/perseverancevictory/p/4246008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!