(1).self
是參照到目前的class,$this是參照到目前的object ( 已經被宣告的實體上 )

(2).self 可使用在static上,$this不行

static method 因為沒有物件的實體,所以需要注意不可以使用 $this ,要用self::
可以直接存取 static method ( 如self::method() ),但是無法直接存取 static property 中的預先宣告的值

(3). 可用 new self() 呼叫自己

 

以下是(1)的範例:

<?
class name
{
    
    public $name;
    
    public function getname(){
        return $this->name = "mick";
    }

    public function getnamebythis(){
        return $this->getname();
    }

    public function getnamebyself(){
        return self::getname();
    }
}

class name2 extends name{
    

    public function getname(){
        return $this->name = "jeff";
    }
}

$newname = new name2();
echo $newname->getnamebythis() . "<br/>"; //
出現的是mick
echo $newname->getnamebyself() . "<br/>"; // 出現的是jeff
?>

 

arrow
arrow
    全站熱搜

    miggo 發表在 痞客邦 留言(7) 人氣()