|
例六:抽象类
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 方法将会被自动调用。
例七:__call
class foo { function __call($name,$arguments) { print("Did you call me? I'm $name!"); } } $x = new foo(); $x->doStuff(); $x->fancy_stuff(); ?> 这个特殊的方法可以被用来实现“过载(overloading)”的动作,这样你就可以检查你的参数并且通过调用一个私有的方法来传递参数。
例八:使用 __call 实现“过载”动作
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
这是一个很棒的方法,__set 和 __get 方法可以用来捕获一个对象中不存在的变量和方法。
例九: __set 和 __get
class foo { function __set($name,$val) { print("Hello, you tried to put $val in $name"); } function __get($name) { print("Hey you asked for $name"); } } $x = new foo(); $x->bar = 3; print($x->winky_winky); ?>
类型指示
在 PHP5 中,你可以在对象的方法中指明其参数必须为另一个对象的实例。
例十:类型指示
class foo { // code ... } class bar { public function process_a_foo(foo $foo) { // Some code } } $b = new bar(); $f = new foo(); $b->process_a_foo($f); ?> 可以看出,我们可以显性的在参数前指明一个对象的名称,PHP5 会识别出这个参数将会要是一个对象实例。
上一页 [1] [2] [3] [4] 下一页 |