PHP中::、->、self、$this操作符
來源:程序員人生 發布時間:2014-02-22 00:53:17 閱讀次數:2429次
在訪問PHP類中的成員變量或方法時,如果被引用的變量或者方法被聲明成const(定義常量)或者static(聲明靜態),那么就必須使用操作符::,反之如果被引用的變量或者方法沒有被聲明成const或者static,那么就必須使用操作符->.
另外,如果從類的內部訪問const或者static變量或者方法,那么就必須使用自引用的self,反之如果從類的內部訪問不為const或者static變量或者方法,那么就必須使用自引用的$this.
$this實例代碼如下:
- <?php
-
- class test_this{
- private $content;
-
- function __construct($content){
- $this->content= $content;
- }
- function __destruct(){}
-
- function printContent(){
- echo $this->content.'<br />';
- }
- }
- $test=new test_this('北京歡迎你!');
- $test->printContent();
::使用方法實例代碼如下:
-
- class test_parent{
- public $name;
- function __construct($name){
- $this->name=$name;
- }
- }
- class test_son extends test_parent{
- public $gender;
- public $age;
- function __construct($gender,$age){
- parent::__construct('nostop');
- $this->gender=$gender;
- $this->age=$age;
- }
- function __destruct(){}
- function print_info(){
- echo $this->name.'是個'.$this->gender.',今年'.$this->age.'歲'.'<br />';
- }
- }
- $nostop=new test_son('女性','22');
- $nostop->print_info();
使用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';的形式.
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈