Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Object property and method call overloading

Object property and method call overloading

Introduction

The purpose of this extension is to allow overloading of object property access and method calls. Only one function is defined in this extension, overload() which takes the name of the class that should have this functionality enabled. The class named has to define appropriate methods if it wants to have this functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a method. This way overloading can be selective. Inside these handler functions the overloading is disabled so you can access object properties normally.

Warning:

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.

Warning:

This extension is not a part of PHP 5. PHP 5 supports __get(), __set() and __call() natively. See the Overloading in PHP 5 page for more information.

Requirements

No external libraries are needed to build this extension.

Installation

In order to use these functions, you must compile PHP with the --enable-overload option. Starting with PHP 4.3.0 this extension is enabled by default. You can disable overload support with --disable--overload.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.

Note:

Builtin support for overload is available with PHP 4.3.0.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Examples

Some simple examples on using the overload() function:

Example 1627. Overloading a PHP class

<?php

class OO {
   var
$a = 111;
   var
$elem = array('b' => 9, 'c' => 42);

   
// Callback method for getting a property
   
function __get($prop_name, &$prop_value)
   {
       if (isset(
$this->elem[$prop_name])) {
           
$prop_value = $this->elem[$prop_name];
           return
true;
       } else {
           return
false;
       }
   }

   
// Callback method for setting a property
   
function __set($prop_name, $prop_value)
   {
       
$this->elem[$prop_name] = $prop_value;
       return
true;
   }
}

// Here we overload the OO object
overload('OO');

$o = new OO;
echo
"\$o->a: $o->a\n"; // print: $o->a: 111
echo "\$o->b: $o->b\n"; // print: $o->b: 9
echo "\$o->c: $o->c\n"; // print: $o->c: 42
echo "\$o->d: $o->d\n"; // print: $o->d:

// add a new item to the $elem array in OO
$o->x = 56;

// instantiate stdclass (it is built-in in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;

// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);

?>


Table of Contents

overload — Enable property and method call overloading for a class

Code Examples / Notes » ref.overload

upphpdoc

While this is a nice Feature it has nothing to do with Overloading as it is known in other OO-Languages.
What this feature does is allowing the dynamic addition of instance variables as e.g in Python.
Overloading means defining several methods with the same name in a single class. Which method will be called depends on the number and type of arguments specified. With dynamic and weak typed languages (like PHP) this can  of course not work.


muell-spam-trash-abfall

This is the syntax of __get(), __set() and __call():
__get ( [string property_name] , [mixed return_value] )
__set ( [string property_name] , [mixed value_to_assign] )
__call ( [string method_name] , [array arguments] , [mixed return_value] )
__call() seems to work with PHP 4.3.0
See http://www.phppatterns.com/index.php/article/articleview/28/1/2/ for using this extension in detail.


fabiostt x_at_x libero x_dot_x it

This extension has not much to do with overloading as we know it in Java or C++
We can sort of mimic overloading using call_user_func_array()
<?php
class OverloadTest{
   var $message ;
   function OverloadTest(){
       $numArgs = func_num_args() ; //number of args
       $args = func_get_args() ;  //array containing args
       call_user_func_array( array( &$this, 'OverloadTest'.$numArgs),  $args) ;
   }
   function overloadTest0(){
      $this->message = 'There are no args' ;
   }
   function overloadTest1($arg){
      $this->message = 'There\'s just one arg, its value is '.$arg ;
   }

function overloadTest2($arg1, $arg2){
      $this->message = 'There are 2 args, their values are '.join( func_get_args(), ', ') ;
   }

function getMessage(){

   return($this->message) ;

}
}//end class
$x = new OverloadTest('fooA', 'fooB') ;
echo( $x->getMessage() ) ;
?>


admin hat solidox dawt org

there are a couple of things you should be aware of when using overloading.
<?
class cTest
{
function __get($key, &$value)
{
echo "get: $key<br />";
return true;
}
function __set($key, $value)
{
echo "set: $key value: $value<br />";
return true;
}
function __call($method, $params, &$return)
{
echo "call: $method params: " . var_export($params, 1) . "<br />";
return true;
}
}
overload('cTest');
$cake = new cTest;
?>
firstly it should be noted that nested classes don't work.
secondly if you try to set an array it somehow becomes a get
and thirdly, if you call a nested class it picks the last nest as the method name, as opposed to a nested get which picks the first in the list.
<?
$x = $cake->hello->moto; //outputs "get: hello" moto is nowhere to be seen
$cake->hello['moto'] = 4; //outputs "get: hello"
$cake->moo->cow("hello"); //outputs "call: cow params: array ( 0 => 'hello', )"
?>
bit strange, these occur on php4.3.2. havn't tried other versions


jw

The following backwards compatible code demonstrates the differences between the PHP version 4 and 5 implementation of overloading:
<?
class Foo {
// The properties array
var $array = array('a' => 1, 'b' => 2, 'c' => 4);
// Getter
function __get($n, $val = "") {
if (phpversion() >= 5) {
return $this->array[$n];
} else {
$val = $this->array[$n];
return true;
}
}

// Setter
function __set($n, $val) {
$this->array[$n] = $val;
if (phpversion() < 5) return true;
}

// Caller, applied when $function isn't defined
function __call($function, $arguments) {
// Constructor called in PHP version < 5
if ($function != __CLASS__) {
$this->$arguments[0] = $arguments[1];
}
if (phpversion() < 5) return true;
}
}
// Call the overload() function when appropriate
if (function_exists("overload") && phpversion() < 5) {
overload("Foo");
}
// Create the object instance
$foo = new Foo;
// Adjust the value of $foo->array['c'] through
// method overloading
$foo->set_array('c', 3);
// Adjust the value of $foo->array['c'] through
// property overloading
$foo->c = 3;
// Print the new correct value of $foo->array['c']
echo 'The value of $foo->array["c"] is: ', $foo->c;
?>


justin b

Some useful things to know about overloading:
__call($m,$p,&$r) returns $r back to you, not whatever you put after the keyword return.  What you return determines whether or not the parser consideres the function defined.
__get($var,&$val) returns $val back to you, so fill up $val with what you want then return true or false, same as above.
when extending classes, you must overload the most extended level class for it to work:
class TestClass
{
   var $x = "x";
   var $y = "y";
   var $z = "z";
   function __call($method,$params,&$return)
   {
       $return = "Hello, you called $method with ".var_export($params,true)."
\n";
       return true;
   }
   function __get($var,&$val)
   {
       if($var == "l") { $val = $this->x; return true; }
       return false;
   }
}
overload('TestClass');
$test = new TestClass;
print $test->hello();
print $test->goodbye();
print $test->x;
print $test->l;
print $test->n;
class Test2 extends TestClass
{
}
$test2 = new Test2;
print $test2->hello();
/* output:
Hello, you called hello with array()
Hello, you called goodbye with array()
xx
Fatal Error: Call to undefined function hello() in ...
*/


kris - heehaw

Simple way to restrict class property access (read and/or write) and range checking on setting, custom get also.
<?php
final class test {
protected $x;
protected $y;
protected $z;
private $publicRead = Array(
'x'=>"",
'y'=>"",
'z'=>"getZ"
);
private $publicWrite = Array(
'x'=>"setX",
'y'=>"setY"
);
final public function test(){
$this->x = 0;
$this->y = 0;
$this->z = 100;
return $this;
}


final public function setX($val){
//allow only 1 - 10
if ($val > 0 && $val < 11){
$this->x = $val;
} else {
echo "Cannot set X to $val, valid range is 1-10\n<br />";
}
}

final public function setY($val){
//allow only 11 - 20
if ($val > 10 && $val < 21){
$this->y = $val;
} else {
echo "Cannot set Y to $val, valid range is 11-20\n<br />";
}
}

final public function getZ(){
return ($this->z*2)." (x2) ";
}

final private function __get($nm)
{
if (array_key_exists($nm, $this->publicRead)){
$method = $this->publicRead[$nm];
if ($method != ""){//if we have a custom get method use it
return $this->$method();
} else { //else return the value directly
return $this->$nm;
}
} else {
echo "Cannot get protected property ".get_class($this)."::$nm\n<br />";
return null;
}
}

final private function __set($nm, $val)
{
if (array_key_exists($nm, $this->publicWrite)){
$method = $this->publicWrite[$nm];
$this->$method($val);
} else {
echo "Cannot set protected property ".get_class($this)."::$nm\n<br />";
}
}
}
$t = new test;
$t->x = 1;
$t->y = 113;
$t->z = 1001;
echo "<br /><br />";
echo "X:".$t->x."<br />";
echo "Y:".$t->y."<br />";
echo "Z:".$t->z."<br />";
?>


metal

Overload and Inheritance.
After wasting a few hours trying to get it to work, it seems appropriate to put a warning here.
Short Version:
DON'T ever subclass an overloaded class. EVER.
Corollary:
If an overloaded class simply must be subclassed, rewrite the parent class to get rid of the overloading. It can be as simple as commenting out the overload() statement and calling the get/set/call methods explicitely.
This was the road I ended up taking.
Long Version:
While it is, in theory, possible to end up with a working subclass, it requires much mucking and OO-principles compromise.
There is a great post that details the problem at great length. For those with the stomach, the URL is:
http://www.zend.com/lists/engine2/200201/msg00140.html
If you're still thinking about mixing inheritance and overloading, at least read the "Best Practices for the overload functions" in the URL above. If that doesn't change your mind, at least you'll be able to avoid most of the pitfalls.


shores

One way to overcome the foreach overloading malfunction:
//non functioning:
foreach ($object->arrayProperty as $key => $value) { ... }
//functioning:
foreach (array_merge($object->arrayProperty) as $key => $value) { ... }
Bye!


josh

One thing about __get is that if you return an array it doesn't work directly within a foreach...
<?php
class Foo {
 function __get($prop,&$ret) {
   $ret = array(1,2,3);
   return true;
 }
}
overload ('Foo');
//works
$foo = new Foo;
$bar = $foo->bar;
foreach($bar as $n) {
 echo "$n \n";
}
//doesn't work (bad argument to foreach)
foreach($foo->bar as $n) {
 echo "$n \n";
}
?>
for loops also work fine..


daniel

Note that with this class:
<?php
class SillyClass
{
private $config = array();

       public function __construct()
{
$this->config['fruit'] = 'banana';
               $this->config['animal'] = 'monkey';
$this->config['shoppingList'] =
              array('drink' => 'milk', 'food' => 'cheeseburger');
}

      //Allow mySillyClass->someProperty style getting of
//anything that might happen to be in the $config array
//(returns NULL if not in the $config array).
public function __get($property)
{
if(isset($this->config->$property))
{
return $this->config->$property;
}
}
}
?>
The following code can not be used:
<?php
$mySillyClass = new SillyClass();
$drinkToBuy = $mySillyClass->shoppingList->drink;
?>
It seems that although there is no error, $mySillyClass->someProperty->someProperty
does *not* work (__get() is only called once).
It's not really a bug, and I'm sure PHP is behaving properly but it had me stumped for a while!


sdavey

It wasn't quite clear, but I found out that __get() and __set() only overload attributes that _don't_ exist.
For example:
<?
class Foo
{
var $a = "normal attribute";
function __get($key, &$ret)
{
$ret = "overloaded return value";
return true;
}
}
overload("Foo");
$foo = new Foo();
print "get a: $foo->a \n"; // prints:   get a: normal attribute
print "get b: $foo->b \n"; // prints:   get b: overloaded return value
?>
The important thing to note here is that $foo->a did not pass through __get(), because the attibute has been defined.
So it's more like "underloading" than "overloading", as it only virtualises attributes that _do not_ exist.


steve

If you are a perfectionist when it comes to your class interfaces, and you are unable to use overload(), there is another viable solution:
Use func_num_args() to determine how many arguments were sent to the function in order to create virtual polymorphism. You can create different scenarios by making logical assumptions about the parameters sent. From the outside the interface works just like an overloaded function.
The following shows an example of overloading a class constructor:
class Name
{
     var $FirstName;
     var $LastName;
     function Name($first, $last)
     {
           $numargs = func_num_args();

           if($numargs >= 2)
           {
                 $this->FirstName = $first;
                 $this->LastName = $last;
           }
           else
           {
                 $names = explode($first);
                 $this->FirstName = $names[0];
                 $this->LastName = $names[1]
           }
     }

}


john martin

I've found a work around that allows overload to work with nested classes.  I was trying to design a set of classes that I didn't need to define the setter/getter methods for each of the properties.  
I stayed away from the __get() and __set() function since this bypasses object encapsulation.  Instead I use the __call() method to implement the accessor functions.  The __call() function emulates the get{var name} and stores the variable into an internal array with in the class.  The get{var name} checks the array for the var name and returns it if found.
Using the Zend Dev Studio (Great Product!) I was able to debug the code and found that when overloaded objects are nested that the nested object somehow looses the array var.  Just for giggles, I added a second variable and assigned the array var by reference.  Some how this worked.  
class Base {
  var $_prop = array();
  var $_fix;
 
  function Base() {
     // This somehow fixes the problem with nested overloading
     $this->_fix = & $this->_prop;  
  }
}


evert

I use the overloader to perform a method-level permission check for objects
<?
class MyClass {
 function method1() {
  // .... //
 }
 function method2() {
 // .... //
 }
}
class ObjectProtector {
   var $obj;
   function ObjectProtector(&$object) {
      $this->obj =& $object;
   }
   function __call($m,$a,&$r) {
      if (myPermissionChecker(...)) {
        $r = call_user_func_array(array($this->obj,$m),$a);
        return true;
      } else return false;
   }
}
 
overload('ObjectProtector');
// Create your object
$myObj = new MyClass;
// Prodect your object
$myProtectedObj = new ObjectProtector($myObj);
//call your methods trough $myProtectedObj
$myProtectedObj->method1();
$myProtectedObj->method2('arguments');
?>
I'm not sure this is bad practice, but the engine allows it and it seems right.


dreamscape

I didn't see this posted anywhere, so here it is:
In PHP 4, if you are calling your overloaded class A from inside class B, you MUST include and overload class A before including class B.
I struggled with this one for some time, before attempting to change the include order of the classes, which then worked great.


none

I am coding a server with a lot of method. To avoid doing a $this->check_auth() call (and others similar processing) in _each_ on my method, I was looking for a way to wrap them all through a dispatch.
Combining _call, with call_user_func_array is the way I did it finally.
So basically, if you want to call "testFunc" you just call $class->test () and
it will be wrapped and testFunc will be executed.
<?php
class MytestClass
{
   function __call($method, $param)
       {
           // do anything here
           return (call_user_func_array (array ("MytestClass", $method."Func"), $param));
       }
   
   function testFunc($param, $arg)
       {
           echo "It works ! Param: $param, ARG=$arg\n";
           return true;
       }
}
$test = new MytestClass;
$test->test ("Cool", "Test");
?>


almethot

Here is a cleaner way to fake overloading which is a modification on fabiostt[X_AT_X]libero[X_DOT_X]it
12-Aug-2003 01:56 posting. This example allows you to reuse the object and not have to re-create the object everytime the variables need to change.
Hope this helps,
<?
Class NCSession
{
//Class Variables
Var $sessionResult = null;
// Sims Overloading in PHP - Yes it is crap but it works until you move to PHP 5.
function ncStartSession()
{
$numArgs = func_num_args() ; //number of args
$args = func_get_args() ;  //array containing args
$x = call_user_func_array( array( &$this, 'ncStartSession'.$numArgs),  $args) ;
$sessionResult = $x;
return $sessionResult;
}
function ncStartSession0()
{
session_start();
$sessionResult = "SUCCESS|YES|SESSIONID|" . session_id();
session_destroy();
return $sessionResult;
}
function ncStartSession1($arg)
{
session_start($arg);
$sessionResult = "SUCCESS|YES|SESSIONID|" . session_id();
session_destroy();
return $sessionResult;
       }
}
//End of Class
$myTestSession = NEW NCSession();
$myResult = $myTestSession->ncStartSession();
echo "\n\$myResult = $myResult\n";
?>


koert

Do not implement __call() if you need pass-by-reference of return-by-reference elswhere in your class.
For more information view php bug #25831. Unfortunately this bug is marked wont-fix.


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker