Home  >  Article  >  Backend Development  >  php技巧之return关键字

php技巧之return关键字

WBOY
WBOYOriginal
2016-06-20 13:01:001075browse

php技巧之return关键字

你肯定知道以下:

return 关键字一般用于返回一个函数的结果,例如:

<?php
function test() {
    return 'this is a string';
}
?>

在类定义的情况下也可以用来返回类实例,例如:

class someClass 
{
    public function method1()
    {
        print 'method one called';
    }
    public function getInstence()
    {
        return $this;
    }
}

$a = new someClass;
$b = $a->getInstence();
$b->method1();
$c = clone($a);
if ($a === $b) { //关于 ' ===' 你可以参照我的文章[基础]php技巧之判断
    print '<br />$a and $b are the same.<br />'; //$a 和 $b 指向了同一个对象实例
}
if ($a !== $c) {
    print '<br />$a and $c are NOT the same.<br />';  //使用克隆clone()之后,生成一个新的对象实例。
}

如果你想简洁一点写函数return,千万别这样写, 编译器会很快告诉你 “Parse error: syntax error, unexpected T_RETURN in E:/web/4.php on line 7

<?php
/**
 * @param integer $a  一个整数
 *
 */
function a ($a) {
    $a<=0 ? return true : return false;
}
?>

这样写才是正确的

<?php
/**
 * @param integer $a  一个整数
 *
 */
function a ($a) {
     return $a<=0 ? true : false;
}
?>

你可能不知道这个

PHP在include或者require文件时,如果被包含文件中的return 关键字不在函数中,那么return 的结果将会被当作include或者require的返回值,这个特性使得被包含文件更像是一个函数,在特殊的情况下可能会用到,看例子:

1.php 被包含文件

<?php 
    $i = 0;
    $number;
    for ($i; $i < 100; $i++) {
        $number++; 
    }
    return $number;
    echo '本行不会被执行';
?>


2.php 

<?php 
    print include '1.php'; //输出结果 100
?>

 


Statement:
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