php技巧之return关键字
你肯定知道以下:
return 关键字一般用于返回一个函数的结果,例如:
<?phpfunction test() { return 'this is a string';}?>
在类定义的情况下也可以用来返回类实例,例如:
clas<p>4本文¥来源gao!%daima.com搞$代*!码$网9</p><pre>搞代gaodaima码
s 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/** * @param integer $a 一个整数 * */function a ($a) { $a这样写才是正确的<?php/** * @param integer $a 一个整数 * */function a ($a) { return $a
你可能不知道这个
PHP在include或者require文件时,如果被包含文件中的return 关键字不在函数中,那么return 的结果将会被当作include或者require的返回值,这个特性使得被包含文件更像是一个函数,在特殊的情况下可能会用到,看例子:
1.php 被包含文件
<?php $i = 0; $number; for ($i; $i
2.php
<?php print include '1.php'; //输出结果 100?>