-
- class foo {
- function __call($name,$arguments) {
- print("Did you call me? I'm $name!
");
- print_r($ arguments);
- print("
");
- }
-
- function doSecond($arguments)
- {
- print("Right, $arguments!
");
- }
- }
-
- $test = new foo();
- $test->doFirst('no this function');
- $test->doSecond('this function exist');
- ?>
Copy code
__call implements the "overload" action
This special method can be used to implement "overloading" actions, so that you can check your parameters and pass them by calling a private method.
Example: Use __call to implement "overload" action
-
- 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!");
- }
- //by bbs.it-home.org
-
- private function foo_for_string($x) {
- print("oh a string!");
- }
- }
-
- $test = new Magic();
- $test->foo(3);
- $test->foo("3");
- ?>
Copy code
2. Usage of __set and __get
This is a great way to use the __set and __get methods to capture variables and methods that don't exist in an object.
Example: __set and __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
");
- }
- }
-
- $test = new foo();
- $test->__set('name',' justcoding');
- $test->__get('name');
- ?>
Copy code
In PHP programming, especially in PHP object-oriented programming, flexibly apply __call, __set and _ _get, you can receive unexpected surprises, it is recommended that everyone grasp it firmly.
|