PHP中::、->、self、$this操作符_PHP教程

來源:互聯網
上載者:User
在訪問PHP類中的成員變數或方法時,如果被引用的變數或者方法被聲明成const(定義常量)或者static(聲明靜態),那麼就必須使用操作符::,反之如果被引用的變數或者方法沒有被聲明成const或者static,那麼就必須使用操作符->。

另外,如果從類的內部訪問const或者static變數或者方法,那麼就必須使用自引用的self,反之如果從類的內部訪問不為const或者static變數或者方法,那麼就必須使用自引用的$this。

$this執行個體

代碼如下 複製代碼

// this是指向當前對象的指標

class test_this{
private $content; //定義變數

function __construct($content){ //定義建構函式
$this->content= $content;
}
function __destruct(){}//定義解構函式

function printContent(){//定義列印函數
echo $this->content.'
';
}
}

$test=new test_this('北京歡迎你!'); //執行個體化對象
$test->printContent();//北京歡迎你!

::使用方法

代碼如下 複製代碼

//parent是指向父類的指標

class test_parent{ //基類
public $name; //定義姓名 父類成員需要定義為public,才能夠在繼承類中直接使用 this來調用。
function __construct($name){
$this->name=$name;
}
}
class test_son extends test_parent{ //衍生類別 繼承test_parent
public $gender;//定義性別
public $age; //定義年齡
function __construct($gender,$age){ //繼承類的建構函式
parent::__construct('nostop');//使用parent調用父類的建構函式,來進行對父類的執行個體化
$this->gender=$gender;
$this->age=$age;
}
function __destruct(){}
function print_info(){
echo $this->name.'是個'.$this->gender.',今年'.$this->age.'歲'.'
';
}
}

$nostop=new test_son('女性','22');//執行個體化test_son對象
$nostop->print_info();//執行輸出函數 nostop是個女性,今年23歲


使用self::$name的形式。注意的是const屬性的申明格式,const PI=3.14,而不是const $PI=3.14

代碼如下 複製代碼

class clss_a {

private static $name="static class_a";

const PI=3.14;
public $value;

public static function getName()
{
return self::$name;
}
//這種寫法有誤,靜態方法不能訪問非靜態屬性
public static function getName2()
{
return self::$value;
}
public function getPI()
{
return self::PI;
}


}

還要注意的一點是如果類的方法是static的,他所訪問的屬性也必須是static的。
在類的內部方法訪問未聲明為const及static的屬性時,使用$this->value ='class_a';的形式。

http://www.bkjia.com/PHPjc/628859.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/628859.htmlTechArticle在訪問PHP類中的成員變數或方法時,如果被引用的變數或者方法被聲明成const(定義常量)或者static(聲明靜態),那麼就必須使用操作符:...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.