<?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