<?php /** * 對象的定義 * */ class Student{ public $PI=3.141592653; //常量定義不加$ const C ="LOVE"; private $name ; private $age ; //構造方法 public function __construct($name,$age){ $this->age=$age; $this->name=$name; } //析構方法 銷燬對象 釋放內存 public function __destruct(){ echo '<h2 style="color:red;">對象被銷燬,調用析構方法!</h2>'; } public function getName (){ return $this->name; } public function setName($name){ $this->name = $name; } public function setAge($age){ /** * 對象->方法名 * 方法名或者變量前不加 $ */ $this->age=$age; } public function getAge(){ return $this->age; } } //實例化 $student = new Student(); $age = 23; $name = "萬年青"; //爲對象的參數賦值 $student->setAge($age); $student->setName($name); echo $student->getAge().'<br>'; echo $student->getName().'<br>'; echo $student->PI.'<br>'; // :: 引用常量 echo Student::C .'<br>'; $s2 =new Student("php", 5); echo '構造方法:'.$s2->getAge();
結果以下圖: php