PHP Overloading

11th December 2009 - 11 minutes read time

Overloading in PHP describes the way in which properties and methods of an object can be dynamically created or accessed without having to define them first. Traditionally, the word overloading in programming is used to describe accessing object methods with the same name but with different parameters. It is not possible to do this in PHP as it will complain about methods having the same name, so the term describes calling a method or accessing a property that hasn't previously been set or is out of scope. In object orientated terms this means that the method or property is private.

Object Property Overloading

Property overloading allows you to access the property of an object through a method without having to write them first. It can also be used to access any properties that are inaccessible. There are two basic property overloading methods available, these are __set() and __get(), both contain a double underscore (_) in their name.

The __set() method is called whenever an undefined or inaccessible property of an object is set and must have the following footprint.

void __set ( string $name , mixed $value )

The __get() method is called whenever an undefined or inaccessible property of an object is read and must have the following footprint.

mixed __get ( string $name )

The following simple class defines both these functions in their simplest form along with a couple of properties. Every time either the __set() or __get() methods are used they will print out some information.

  1. class OverloadingTest
  2. {
  3. private $privateProperty;
  4.  
  5. public $publicProperty;
  6.  
  7. public function __set($name, $value)
  8. {
  9. echo '__set() ' . $name . ' ' . $value. "\n";
  10. $this->$name = $value;
  11. }
  12.  
  13. public function __get($name)
  14. {
  15. echo '__get() ' . $name . "\n";
  16. return $this->$name;
  17. }
  18. }

To test these functions I wrote some simple code.

  1. $object = new OverloadingTest();
  2. $object->privateProperty = 'this is a private value';
  3. echo $object->privateProperty . "\n";
  4.  
  5. $object->publicProperty = 'this is a publicvalue';
  6. echo $object->publicProperty . "\n";
  7.  
  8. $object->nonExistingProperty = 'another value';
  9. echo $object->nonExistingProperty . "\n";
  10.  
  11. var_dump($object);

This code creates the following output.

  1. __set() privateProperty this is a private value
  2. __get() privateProperty
  3. this is a private value
  4. this is a publicvalue
  5. __set() nonExistingProperty another value
  6. another value
  7. object(OverloadingTest)#1 (3) {
  8. ["privateProperty:private"]=>
  9. string(23) "this is a private value"
  10. ["publicProperty"]=>
  11. string(21) "this is a publicvalue"
  12. ["nonExistingProperty"]=>
  13. string(13) "another value"
  14. }

One very important thing to note is that when a property is created using __set(), the __get() is not used to retrieve the value of the property. For this reason you might see some classes created like this, where a private property is created as an array and the __get() and __set() methods access this property.

  1. class OverloadingTest2
  2. {
  3. private $privateProperty = array();
  4.  
  5. public function __set($name, $value)
  6. {
  7. echo '__set() ' . $name . ' ' . $value. "\n";
  8. $this->privateProperty[$name] = $value;
  9. }
  10.  
  11. public function __get($name)
  12. {
  13. echo '__get() ' . $name . "\n";
  14. if (!isset($this->privateProperty[$name])) {
  15. return null;
  16. }
  17. return $this->privateProperty[$name];
  18. }
  19. }

This forces the __get() method to be used when reading the property of the parameter, rather than it being ignored as in the previous example. The outside code looks very similar to the previous code, but the class that controls the data stores it in a different way.

  1. $object = new OverloadingTest2();
  2. $object->property = 'this is a value';
  3. echo $object->property . "\n";
  4.  
  5. var_dump($object);

This produces the following output.

  1. __set() property this is a private value
  2. __get() property
  3. this is a private value
  4. object(OverloadingTest)#1 (1) {
  5. ["property:private"]=>
  6. array(1) {
  7. ["property"]=>
  8. string(15) "this is a value"
  9. }
  10. }

If you are used to object orientation you might have seen something called chaining, especially where set type methods are used. This doesn't work using the __set() method as any return values are ignored and the $value parameter sent to the method is returned instead. The following method would return the value of the $value parameter an NOT the current object.

  1. public function __set($name, $value)
  2. {
  3. echo '__set() ' . $name . ' ' . $value . "\n";
  4. $this->privateProperty[$name] = $value;
  5. return $this;
  6. }

Two other property overloading methods exist, these are called __isset() and __unset(), which have been available since PHP version 5.1.0. The __isset() method is called when isset() or empty() is called on innacessible properties and must have the following footprint.

bool __isset ( string $name )

The __unset() method is called when the unset() function is called on inaccessible properties and has the following footprint.

void __unset ( string $name )

With this information in hand we can modify our class to include these functions.

  1. class OverloadingTest3
  2. {
  3. private $privateProperty = array();
  4.  
  5. public function __set($name, $value)
  6. {
  7. echo '__set() ' . $name . ' ' . $value. "\n";
  8. $this->privateProperty[$name] = $value;
  9. return $this;
  10. }
  11.  
  12. public function __get($name)
  13. {
  14. echo '__get() ' . $name . "\n";
  15. if (!isset($this->privateProperty[$name])) {
  16. return null;
  17. }
  18. return $this->privateProperty[$name];
  19. }
  20.  
  21. public function __isset($name) {
  22. echo '__isset() ' . $name . "\n";
  23. return isset($this->privateProperty[$name]);
  24. }
  25.  
  26. public function __unset($name) {
  27. echo '__unset() ' . $name . "\n";
  28. unset($this->privateProperty[$name]);
  29. }
  30. }

We can test these new functions like this.

  1. $object = new OverloadingTest3();
  2. $object->property = 'this is a value';
  3. echo $object->property . "\n";
  4.  
  5. var_dump(isset($object->property));
  6. unset($object->property);
  7. var_dump(isset($object->property));
  8.  
  9. var_dump($object);

This produces the following output.

  1. __set() property this is a value
  2. __get() property
  3. this is a value
  4. __isset() property
  5. bool(true)
  6. __unset() property
  7. __isset() property
  8. bool(false)
  9. object(OverloadingTest3)#1 (1) {
  10. ["privateProperty:private"]=>
  11. array(0) {
  12. }
  13. }

Object Method Overloading

Method overloading works in much the same way as property overloading, but is obviously used on non-existent or inaccessible methods. By adding a method called __call() to your class you can intercept any calls to inaccessible methods. The __call() method must have the following footprint.

mixed __call ( string $name , array $arguments )

The $name parameter will contain the name of the function called and is case sensitive, the $arguments parameter will contain an array of any arguments sent to the method call. The following is a very simple example of this method in action.

  1. class OverloadMethodTest
  2. {
  3. public function __call($name, $arguments)
  4. {
  5. echo '__call ' . $name . "\n";
  6. print_r($arguments);
  7. }
  8. }
  9.  
  10. $obj = new OverloadMethodTest();
  11. $obj->runSomething('parameter1', 2);

This will produce the following output.

  1. __call runSomething
  2. Array
  3. (
  4. [0] => parameter1
  5. [1] => 2
  6. )

Out of interest I wondered what would happen if I added a private method called runSomething() to the class and tried to run the same code.

  1. class OverloadMethodTest
  2. {
  3. public function __call($name, $arguments)
  4. {
  5. echo '__call ' . $name . "\n";
  6. print_r($arguments);
  7. }
  8.  
  9. private function runSomething()
  10. {
  11. echo 'runSomething() is a private method';
  12. }
  13. }
  14.  
  15. $obj = new OverloadMethodTest();
  16. $obj->runSomething('parameter1', 2);

This produced exactly the same output as before, which means that the __call() method intercepts any calls to existing private methods rather than produce a fatal error about accessing private methods.

As of PHP 5.3.0 there is also a method called __callStatic() that can be used to provide the same sort of functionality to static method calls that __call() provides. The __callStatic() method also has the same footprint as the __call() method and is called in the same way.

mixed __callStatic ( string $name , array $arguments )

Here is a simple class that uses __callStatic().

  1. class OverloadMethodTest
  2. {
  3. public function __call($name, $arguments)
  4. {
  5. echo '__call ' . $name . "\n";
  6. print_r($arguments);
  7. }
  8.  
  9. public static function __callStatic($name, $arguments)
  10. {
  11. echo '__callStatic ' . $name . "\n";
  12. print_r($arguments);
  13. }
  14. }
  15.  
  16. $obj = new OverloadMethodTest();
  17. $obj->runSomething('parameter1', 2);
  18. OverloadMethodTest::runSomething('in static context');

This produces the following output.

  1. __call runSomething
  2. Array
  3. (
  4. [0] => parameter1
  5. [1] => 2
  6. )
  7. __callStatic runSomething
  8. Array
  9. (
  10. [0] => in static context
  11. )

There is one thing you can't call a method that would go through the __call() method from within the __call() method. In other words, recursive calls to __call() don't work. You can try running it yourself to see what happens using this code.

  1. class OverloadMethodTest2
  2. {
  3. public function __call($name, $arguments)
  4. {
  5. echo '__call ' . $name . "\n";
  6. $this->wibble($name);
  7. print_r($arguments);
  8. }
  9. }
  10.  
  11. $obj = new OverloadMethodTest2();
  12. $obj->runSomething('parameter1', 2);

You will simply receive a null response from your server when running this code.

It is possible to call inaccessible methods from within the same object, you just need to do this from a different method. The following code shows an example of this that works.

  1. class OverloadMethodTest3
  2. {
  3. public function __call($name, $arguments)
  4. {
  5. echo '__call ' . $name . "\n";
  6. print_r($arguments);
  7. }
  8.  
  9. public function test()
  10. {
  11. $this->runSomething('parameter1', 2);
  12. }
  13. }
  14.  
  15. $obj = new OverloadMethodTest3();
  16. $obj->test();

This produces the following output.

  1. __call runSomething
  2. Array
  3. (
  4. [0] => parameter1
  5. [1] => 2
  6. )

This makes sense as the code runs the test() method, which in turn runs the runSomething() method.

Of course it can be a little dangerous to simply allow your classes to process any method name that is run against them. For this reason it is best to employ a switch statement inside the __call() method in order to stop any methods being run that you haven't allowed for. The following example shows this in action.

  1. class OverloadMethodTest4
  2. {
  3. public function __call($name, $arguments)
  4. {
  5. switch ($name) {
  6. case 'function1':
  7. // do something with $arguments
  8. break;
  9. }
  10. }
  11. }

If you want to know more about overloading then you can take a look at the overloading manual page on the PHP website.

Comments

Permalink
Thanks for this, it really helped me learn about overloading in php, I had no prior overloading experience and I though it was well explained.. "bookmarked"

e0je (Mon, 09/13/2010 - 08:18)

Permalink
Really this articale is so much helpfull for me to understanding the Overloading the properties in php...Can you explain me about the stdClass() in php... Thanking you much... Regards

Satish sojitra (Tue, 02/08/2011 - 06:42)

Permalink

Glad you liked it. The stdClass(), since you asked, is a generic empty class that can be used anywhere in PHP. It doesn't have any methods or properties of its own and is intended to be used as a container.

It can be used right out of the box like this:

  1. $object = new stdClass();
  2. $object->property = 'wibble';

Or is can also created when you cast anything as an object, like this:

  1. $array = array('property' => 'wibble');
  2. $object = (object)$array;
  3. echo $object->property;

Actually, it does have one property called "scalar", which is created when a string is cast as an object, like this:

  1. $object = (object)'wibble';
  2. echo $object->scalar; // prints 'wibble'
Permalink

Good Article. Excellent

Suganya (Wed, 07/06/2011 - 10:16)

Add new comment

The content of this field is kept private and will not be shown publicly.