一些内建方法:
1 class Person { 2 public $isAlive = true; 3 4 function __construct($name) { 5 //这里我们创建了一个name的属性 6 $this->name = $name; 7 } 8 //dance方法 返回一个值 9 public function dance() { 10 return "I'm dancing!"; 11 } 12 } 13 //实例化一个me类 14 $me = new Person("Shane"); 15 //is_a判断$me是否属于Person类 16 if (is_a($me, "Person")) { 17 echo "I'm a person, "; 18 } 19 //property_exists判断$me是否有name这个属性 20 if (property_exists($me, "name")) { 21 echo "I have a name, "; 22 } 23 //判断方法是否存在 24 if (method_exists($me, "dance")) { 25 echo "and I know how to dance!"; 26 }
继承:
1 class Shape { 2 //属性 3 public $hasSides = true; 4 } 5 //Square类继承了Shape类 通过extends关键字实现 6 class Square extends Shape { 7 8 } 9 10 $square = new Square(); 11 // 判断如果存在hassides属性 就输出句子 12 if (property_exists($square,"hasSides") ) { 13 echo "I have sides!"; 14 }
1 class Vehicle { 2 static function honk() { 3 return "HONK HONK!"; 4 } 5 } 6 class Bicycle extends Vehicle{ 7 public function bonk(){ 8 return "Beep beep!"; 9 } 10 11 } 12 13 $bicycle = new Bicycle(); 14 // Bicycle类 继承了Vehicle类的方法 15 echo $bicycle->honk();
:
1 class Person { 2 3 } 4 class Ninja extends Person { 5 // Add your code here... 6 const stealth = "MAXIMUM"; 7 8 } 9 // 访问类当中的常量 不需要实例化 10 echo Ninja::stealth; 11 12 13 class King { 14 // Modify the code on line 10... 15 public static function proclaim() { 16 echo "A kingly proclamation!"; 17 } 18 } 19 // 调用方法 不需要实例化 20 echo King::proclaim();