php中的魔术变量小结
php中,有不少很好用的魔术变量,用好之,能事半功倍,下面小结之:
1 _line_
显示当前代码的行数:
echo this is line number : . __line__;
2 _file_
显示当前文件的路径
3 _method_
显示当前方法的名,比如
class magicconstant
{
function __construct()
{
echo this is function a;
}
function b()
{
echo
;
echo this is function b;
echo
;
echo __method__;
}
}
$cm = new magicconstant();
$cm->b();
显示
this is function a
this is function b
magicconstant::b
4 _function_
显示当前所在函数的名
function b()
{
echo
;
echo this is function b;
echo
;
echo __function__;
}
输出:
this is function b
magicconstant::b
5 _dir_
显示当前目录名,如
echo the directory name is : . __dir__;
输出:
the directory name is : d:\wamp\www
6 _class_
显示当前的类
class magicconstant
{
function __construct()
{
echo the class name is : .__class__;
}
}
$cm = new magicconstant();
显示:
the class name is : magicconstant
7 _namespace_
显示当前命名空间
namespace magicconstant
{
echo the namespace is : .__namespace__;
}
输出:
the namespace is : magicconstant
8 _sleep_
_sleep_用在将类序列化之前,
username = $name;
}
function setaddress($address='')
{
$this->useraddress = $address;
}
function setphone($phone='')
{
$this->userphone = $phone;
}
function __sleep()
{
return array('useraddress','userphone');
// this will serialize only address and phone number but not name
}
}
?>
setname('avinash');
$user->setaddress('address here');
$user->setphone('1234567890');
$serialdata = serialize($user);
echo $serialdata;
?>
output: o:4:user:2:{s:11:useraddress;s:12:address here;s:9:userphone;s:10:1234567890;}
程序运行时, serialize() 检查类中是否有 __sleep() ,如果有,则该函数将在任何序列化之前运行. 该函数必须返回一个需要进行序列化保存的成员属性数组,并且只序列化该函数返回的这些成员属性. 该函数有两个作用: 第一. 在序列化之前,关闭对象可能具有的任何数据库连接等. 第二. 指定对象中需要被序列化的成员属性,如果某个属性比较大而不需要储存下来,可以不把它写进__sleep()要返回的数组中,这样该属性就不会被序列化
又如:
class test {
public $mysecret; //我的秘密不想让人知道
public function __construct($secret) {
$this->mysecret = $secret;
}
public function __sleep() {
$this->mysecret = 你休想知道我的秘密!;
return array('mysecret'); //一定要返回变量,不然返回的是个空,所以序列化也就没有东西了。
}
}
$test = new test(我的心里话 我爱某某某);
echo serialize($test); //输出 o:4:test:1:{s:8:mysecret;s:28:你休想知道我的秘密!;}
_wakeup_
用在反序列化时:
username = $name;
}
function setaddress($address='')
{
$this->useraddress = $address;
}
function setphone($phone='')
{
$this->userphone = $phone;
}
function __sleep()
{
return array('useraddress','userphone');
// this will serialize only address and phone number but not name
}
function __wakeup()
{
echo in wakeup function.
;
}
}
?>
setname('avinash');
$user->setaddress('address here');
$user->setphone('1234567890');
$serialdata = serialize($user);
echo $serialdata;
echo
;
var_dump(unserialize($serialdata));
?>
output:
in wakeup function
object(user)#2 (3) {
[username]=>
string(0)
[useraddress]=>
string(12) address here
[userphone]=>
string(10) 1234567890
}