PHPBuilder - Introduction to PHP5 Page 5



RSS Twitter
Articles Tricks And Hacks

Introduction to PHP5 - Page 5

by: Luis Argerich
|
April 11, 2003

__call

In PHP5 the special __call() method can be implemented in a class as a "catch all" method for methods not implemented in the class. If you call a method not accessible or a method that doesn't exist the __call method (if defined) will be called.
Example 7: __call

<?php
class foo {

  function 
__call($name,$arguments) {
    print(
"Did you call me? I'm $name!");
  }
}

$x = new foo();
$x->doStuff();
$x->fancy_stuff();
?>
This special method can be used to implement method overloading because you can examine the arguments and call a private ad-hoc method depending on the arguments passed, example.
Exampe 8: Overloading methods with __call

<?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 and __get

And this gets even fancier, the __set and __get methods can be implemented as catch-all methods for accessing or setting variables not defined (or not accessible).
Example 9: __set and __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);
?>

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Luis Argerich

Comment:



Comment:

(Maximum characters: 1200). You have characters left.