Usage of php _ call, _ set, and _ get

Source: Internet
Author: User
Usage of php _ call, _ set, and _ get

  1. Class foo {
  2. Function _ call ($ name, $ arguments ){
  3. Print ("Did you call me? I'm $ name!
    ");
  4. Print_r ($ arguments );
  5. Print ("

    ");
  6. }
  7. Function doSecond ($ arguments)
  8. {
  9. Print ("Right, $ arguments!
    ");
  10. }
  11. }
  12. $ Test = new foo ();
  13. $ Test-> doFirst ('No this function ');
  14. $ Test-> doSecond ('This function exist ');
  15. ?>

_ 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 ".

  1. Class Magic {
  2. Function _ call ($ name, $ arguments ){
  3. If ($ name = 'Foo '){
  4. If (is_int ($ arguments [0]) $ this-> foo_for_int ($ arguments [0]);
  5. If (is_string ($ arguments [0]) $ this-> foo_for_string ($ arguments [0]);
  6. }
  7. }
  8. Private function foo_for_int ($ x ){
  9. Print ("oh an int! ");
  10. }
  11. // By bbs.it-home.org
  12. Private function foo_for_string ($ x ){
  13. Print ("oh a string! ");
  14. }
  15. }
  16. $ Test = new Magic ();
  17. $ Test-> foo (3 );
  18. $ Test-> foo ("3 ");
  19. ?>

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

  1. Class foo {
  2. Function _ set ($ name, $ val ){
  3. Print ("Hello, you tried to put $ val in $ name
    ");
  4. }
  5. Function _ get ($ name ){
  6. Print ("Hey you asked for $ name
    ");
  7. }
  8. }
  9. $ Test = new foo ();
  10. $ Test->__ set ('name', 'justencoding ');
  11. $ Test->__ get ('name ');
  12. ?>

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.