Introduction to the usage of php __call, __set and __get

WBOY
Release: 2016-07-25 08:59:47
Original
1149 people have browsed it
  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. ?>
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

  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. ?>
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

  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',' justcoding');
  11. $test->__get('name');
  12. ?>
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.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!