程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP中::、->、self、$this操作符

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

編輯:關於PHP編程

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

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

$this實例

 代碼如下 復制代碼

<?php

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

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();//北京歡迎你!

::使用方法

 代碼如下 復制代碼

//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.'歲'.'<br />';
    }
}

$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';的形式。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved