Usage of php _ call, _ set, and _ get
- 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 ');
- ?>
_ Call: This special method can be used to implement an "overload" action, in this way, you can check your parameters and pass the parameters by calling a private method.
For example, use _ call to achieve "overload ".
- 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 ");
- ?>
2. the usage of _ set and _ get is a great method. the __set and _ get methods can be used to capture non-existent variables and methods 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', 'justencoding ');
- $ Test->__ get ('name ');
- ?>
In php programming, especially php object-oriented programming, the flexible application of _ call, _ set, and _ get can surprise you, and we recommend that you master it. |