Example 5: 接口
<?php
interface displayable {
function display();
}
interface printable {
function doprint();
}
class foo implements displayable,printable {
function display() {
// code
}
function doprint() {
// code
}
}
?>
这对代码的阅读性和理解性是非常有帮助的:读到该类时,你就知道foo包含了接口displayable和printable,而且一定有print()(二泉 注:应该是doprint())方法和display()方法。不必知道它们内部是如何实现就可轻松操作它们只要你看到foo的声明。
虚拟类
虚拟类是一种不能被实例化的类,它可以像超类一样,可以定义方法和变量。
在虚拟类中还可以定义虚拟的方法,而且在该方法也不能在该类是被实现,但必须在其子类中被实现
Example 6: 虚拟类
<?php
abstract class foo {
protected $x;
abstract function display();
function setX($x) {
$this->x = $x;
}
}
class foo2 extends foo {
function display() {
// Code
}
}
?>
__call()方法
在PHP5时,如果你定义了 __call()方法,当你试图访问类中一个不存在的变量或方法时,__call()就会被自动调用:
Example 7: __call
<?php
class foo {
function __call($name,$arguments) {
print("Did you call me? I'm $name!");
}
}
$x = new foo();
$x->doStuff();
$x->fancy_stuff();
?>
这个特殊的方法被习惯用来实现"方法重载",因为你依靠一个私有参数来实现并检查这个参数:
Exampe 8: __call 实现方法重载
<?php
class Magic {
function __call($name,$arguments) {
if($name=='foo') {
if(is_int($arguments[0])) $this->foo_for_int($arguments[0]);
if(is_string($arguments[0])) $this->foo_for_string($arguments[0]);
}
}
private function foo_for_int($x) {
print("oh an int!");
}
private function foo_for_string($x) {
print("oh a string!");
}
}
$x = new Magic();
$x->foo(3);
$x->foo("3");
?>
__set()方法 和 __get()方法
当访问或设置一个未定义的变量时,这两个方法将被调用:
Example 9: __set and __get
<?php
class foo {
function __set($name,$val) {
print("Hello, you tried to put $val in $name");
}







