本文實(shí)例講述了PHP面向?qū)ο蟪绦蛟O(shè)計(jì)類的定義與用法。分享給大家供大家參考,具體如下:
<?phpclass Person {  private $name;  private $sex;  private $age;  function __construct($name = "", $sex = "男", $age = 22) {    $this->name = $name;    $this->sex = $sex;    $this->age = $age;  }  // 直接為私有屬性賦值時(shí)自動(dòng)調(diào)用,可以屏蔽一些非法賦值  // 之前有版本可以設(shè)置方法為private function __set()  // The magic method __set() must have public visibility  // 因?yàn)?.35對(duì)魔術(shù)方法限制的嚴(yán)格了  public function __set($propertyName, $propertyValue) {    if ($propertyName == "sex") {      if (! ($propertyValue == "男" || $propertyValue == "女")) {        return;      }      if ($propertyValue > 150 || $propertyValue < 0) {        return;      }    }    // 根據(jù)傳入的成員屬性名,賦上相應(yīng)的值    $this->$propertyName = $propertyValue;  }  // 用來(lái)獲取私有屬性  public function __get($propertyName) {    if (isset ( $this->$propertyName )) {      return ($this->$propertyName);    } else {      return (NULL);    }  }  public function __isset($propertyName) {    if ($propertyName == "name") {      return false; // 返回假,不允許在對(duì)象外部測(cè)定這個(gè)屬性    }    return isset ( $this->$propertyName );  }  public function __unset($propertyName) {    if($propertyName=="name") {      return; //不允許刪除name屬性    }    unset($this->$propertyName);  }  function say() {    echo $this->name . "在說(shuō)話<br/>";  }  function run() {    echo "在走路·<br/>";  }  function __destruct() {    echo "goodbye" . $this->name . "<br/>";  }}$person1 = new Person ();$person2 = new Person ( "2" );$person3 = new Person ( "3" );// 自動(dòng)調(diào)用了__set()$person1->name = "張三";echo $person1->name;echo "<br/>";echo $person1->say ();// 自動(dòng)調(diào)用了__get()echo $person1->age;echo "<br/>";var_dump ( isset ( $person1->name ) );echo "<br/>";unset($person1->name);echo "unset------------>".$person1->name;//name 沒(méi)有被unset()echo "<br/>";$person2 = null;?>結(jié)果:
張三張三在說(shuō)話22bool(false)unset------------>張三goodbye2goodbye3goodbye張三
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選