php :: $this-> self:: parent:: 区别

在访问PHP类中的成员变量或方法时,如果被引用的变量或者方法被声明成const(定义常量)或者static(声明静态),那么就必须使用操作符::,

反之如果被引用的变量或者方法没有被声明成const或者static,那么就必须使用操作符->。
 
举例:如调用静态方法或属性时
 

::域运算符,调用类中的静态属性或方法时使用

 
1.$this->  调用本类中的属性或方法
2.self::    调用本类中的静态属性或方法
3.parent::   调用父类中的静态属性或方法
 
代码示例:
class human
{
    public $_name;
    public function __construct($_name){    //父类构造函数
        $this->_name = $_name;
    }
    static function showName()     //父类静态方法
    {
        print("hello");
    }
};
 
class person extends human       //继承human父类
{
    private static $sex = "male";     //定义静态属性
    private $_sex;       //非静态
    private $_age;       //非静态
 
    public function __construct($_sex,$_age)
    {
        parent::__construct("xqs");     //调用父类构造方法,使用parent::
 
        $this->_sex = $_sex;
        $this->_age = $_age;
    }
 
    public function showPerson()
    {
        print($this->_name.' and '.self::$sex.' and '.$this->_age);//$sex是本类中的静态方法,用self::
    }
};
 
$show = new person("female","19");  //实例化对象
$show->showPerson();
 
注意细节:
父类成员属性都是public的,是为了供继承类通过this来访问。

 

posted @ 2014-02-22 14:38  Mrxia  阅读(108)  评论(0)    收藏  举报