<?php class foo { private $x; public function public_foo() { print("I'm public"); } protected function protected_foo() { $this->private_foo(); //Ok because we are in the same class we can call private methods print("I'm protected"); } private function private_foo() { $this->x = 3; print("I'm private"); } } class foo2 extends foo { public function display() { $this->protected_foo(); $this->public_foo(); // $this->private_foo(); // Invalid! the function is private in the base class } } $x = new foo(); $x->public_foo(); //$x->protected_foo(); //Invalid cannot call protected methods outside the class and derived classes //$x->private_foo(); //Invalid private methods can only be used inside the class $x2 = new foo2(); $x2->display(); ?>
<?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); ?>