php技巧之return关键字
你肯定知道以下:
return 关键字一般用于返回一个函数的结果,例如:
在类定义的情况下也可以用来返回类实例,例如:
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 '
$a and $b are the same.
'; //$a 和 $b 指向了同一个对象实例
}
if ($a !== $c) {
print '
$a and $c are NOT the same.
'; //使用克隆clone()之后,生成一个新的对象实例。
}
如果你想简洁一点写函数return,千万别这样写, 编译器会很快告诉你 “Parse error: syntax error, unexpected T_RETURN in E:/web/4.php on line 7”
这样写才是正确的
你可能不知道这个
PHP在include或者require文件时,如果被包含文件中的return 关键字不在函数中,那么return 的结果将会被当作include或者require的返回值,这个特性使得被包含文件更像是一个函数,在特殊的情况下可能会用到,看例子:
1.php 被包含文件
2.php
输出结果 100
?>
本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉
本文系统来源:php中文网