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免费学习笔记(深入)”;
源码科技中英双语通用企业网站是采用PHP+MYSQL进行开发的。支持伪静态设置,可生成google和百度地图,支持自定义url、关键字和描述,利于收录...后台简单明了,代码简洁,采用DIV+CSS 利于SEO,企业建站系统是一套专门用于中小企业网站建设的网站管理系统。
<?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
?>










