标签:
__toString()适用于直接输出类,用此方法,可以避免出错;__call()适用于使用类当中没有定义的函数(方法)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>__toString()与__call()</title>
</head>
<body>
<?php
class Point{
public function __toString(){
//注意__toString()必须要有返回值,并且输出类时是输出返回的内容
// return __CLASS__;//返回当前类名
return "ok";
}
public function test(){
echo "执行的是已存在的函数!<br>";
}
public function __call($function,$paremeter){
//注意__call()需要两个参数,$function为使用的方法,$parameter为参数,参数可以使对象、数组或者字符串
//可添加需要的操作
echo "类中未定义此函数!<br>";
//echo $function;//输出未定义的函数名
}
}
//__toString()
$point=new Point();
echo $point;//输出ok
//__call()
$point->test();//输出 执行的是已存在的函数!
$point->test("hello");//输出 执行的是已存在的函数!
$point->tank("yes","no");//输出类中未定义此函数!
?>
</body>
</html>
注意,如果未在类当中定义__toString()时,则echo $point;将会出错,提示错误信息为:
Catchable fatal error: Object of class Point could not be converted to string in.......
如果未在类当中定义__call()时,执行$point->tank("yes","no")会出错,错误信息为:
Fatal error: Call to undefined method Point::tank() in......
标签:
原文地址:http://www.cnblogs.com/-beyond/p/5721983.html