1.$this的意思就是本身,所以$this->只可以在类的内部使用,当类被实例化后,$this同时被实例化为本类的对象,这时对$this使用get_class()函数,将返回本类的类名。例:
<?php
Class example{
Function exam(){
If(isset($this)){
Echo ‘$this的值为:’.get_class($this);
}
Else{
Echo ‘$this未定义’;
}
}
}
$class_name = new example();
$class_name->exam();
?>
结果:$this的值为:example。
Get_class()函数返回对象所属类的名字,如果不是对象,则返回false。
2.作用域操作符“::”
相对伪变量$this只能在类的内部使用,操作符”::”更为强大。操作符“::”可以在没有声明任何实例的情况下访问类中的成员方法或成员变量。格式:关键字::变量名/常量名/方法名
关键字可分为3中情况:
1.parent:可以调用父类中的成员变量、成员方法和常量
2.Self:可以调用当前类中的静态成员和常量
3.类名:可以调用本类中的变量、常量和方法。
例:
<?php
Class Book{
Const NAME = ‘computer’;
Function __construct(){
Echo “本月图书类冠军为:”.’Book::NAME’;
}
}
Class l_book extends Book{
Const NAME = ‘foreign language’;
Function __construct(){
Parent::__construct();
Echo ‘本月图书类冠军为:’.self::NAME.’;
}
}
$obj = new l_book();
?>
结果:本月图书类冠军为:computer 本月图书类冠军为:foreign language