PHP物件導向程式設計類的定義與用法詳解

來源:互聯網
上載者:User
這篇文章主要介紹了PHP物件導向程式設計類的定義與用法,結合執行個體形式分析了php類的定義、執行個體化、__set()及__get()具體提示,需要的朋友可以參考下

具體如下:

<?phpclass Person {  private $name;  private $sex;  private $age;  function __construct($name = "", $sex = "男", $age = 22) {    $this->name = $name;    $this->sex = $sex;    $this->age = $age;  }  // 直接為私人屬性賦值時自動調用,可以屏蔽一些非法賦值  // 之前有版本可以設定方法為private function __set()  // The magic method __set() must have public visibility  // 因為5.35對魔術方法限制的嚴格了  public function __set($propertyName, $propertyValue) {    if ($propertyName == "sex") {      if (! ($propertyValue == "男" || $propertyValue == "女")) {        return;      }      if ($propertyValue > 150 || $propertyValue < 0) {        return;      }    }    // 根據傳入的成員屬性名,賦上相應的值    $this->$propertyName = $propertyValue;  }  // 用來擷取私人屬性  public function __get($propertyName) {    if (isset ( $this->$propertyName )) {      return ($this->$propertyName);    } else {      return (NULL);    }  }  public function __isset($propertyName) {    if ($propertyName == "name") {      return false; // 返回假,不允許在對象外部測定這個屬性    }    return isset ( $this->$propertyName );  }  public function __unset($propertyName) {    if($propertyName=="name") {      return; //不允許刪除name屬性    }    unset($this->$propertyName);  }  function say() {    echo $this->name . "在說話<br/>";  }  function run() {    echo "在走路·<br/>";  }  function __destruct() {    echo "goodbye" . $this->name . "<br/>";  }}$person1 = new Person ();$person2 = new Person ( "2" );$person3 = new Person ( "3" );// 自動調用了__set()$person1->name = "張三";echo $person1->name;echo "<br/>";echo $person1->say ();// 自動調用了__get()echo $person1->age;echo "<br/>";var_dump ( isset ( $person1->name ) );echo "<br/>";unset($person1->name);echo "unset------------>".$person1->name;//name 沒有被unset()echo "<br/>";$person2 = null;?>

結果:

張三張三在說話22bool(false)unset------------>張三goodbye2goodbye3goodbye張三

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.