PHP - Overloading Method Calls with __call()

Introduction

You can use __call() to handle calls to nonexistent methods of a class.

__call() accepts the nonexistent method name as a string, and any arguments passed to the nonexistent method as an array.

The method should then return a value if any back to the calling code:

public function __call($methodName, $arguments) {
  // (do stuff here)
  return $returnVal;
}

__call() is useful to create a "wrapper" class that doesn't contain much functionality of its own.

Demo

<?php
        class CleverString {

          private $_theString ="";
          private static $_allowedFunctions = array("strlen","strtoupper","strpos");

          public function setString($stringVal) {
            $this->_theString = $stringVal;
          }//from  ww w .j  av  a  2 s.  c om

          public function getString() {
            return $this->_theString;
          }

          public function __call($methodName, $arguments) {
            if (in_array($methodName, CleverString::$_allowedFunctions)) {
              array_unshift($arguments, $this->_theString);
              return call_user_func_array($methodName, $arguments);
            } else {
              die ("Method'CleverString::$methodName'doesn't exist\n");
            }
          }
        }

        $myString = new CleverString;
        $myString->setString("Hello!");
        echo"The string is:". $myString->getString()."\n";
        echo"The length of the string is:". $myString->strlen()."\n";
        echo"The string in uppercase letters is:". $myString->strtoupper()."\n";
        echo"The letter'e'occurs at position:". $myString->strpos("e")."\n";
        $myString->madeUpMethod();
?>

Result

Related Topic