<?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
这是一个很棒的方法,__set 和 __get 方法可以用来捕获一个对象中不存在的变量和方法。
例九: __set 和 __get
<?php
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 中,你可以在对象的方法中指明其参数必须为另一个对象的实例。
例十:类型指示
<?php
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);
?>