PHP also supports method overloading through the _ _call() callback. This means that if you invoke a method of an object and that method does not exist, _ _call() will be called instead. A trivial use of this functionality is in protecting against undefined methods. The following example implements a _ _call() hook for a class that simply prints the name of the method you tried to invoke, as well as all the arguments passed to the class: class Test {
public function _ _call($funcname, $args)
{
print "Undefined method $funcname called with
If you try to execute a nonexistent method, like this: $obj = new Test;
$obj->hello("george");
you will get the following output: Undefined method hello called with vars: Array ( [0] => george ) _ _call() handlers are extremely useful in remote procedure calls (RPCs), where the exact methods supported by the remote server are not likely to know when you implement your client class. RPC methods are covered in depth in Chapter 16, "RPC: Interacting with Remote Services." To demonstrate their usage here briefly, you can put together an OO interface to Cisco routers. Traditionally, you log in to a Cisco router over Telnet and use the command-line interface to configure and maintain the router. Cisco routers run their own proprietary operating system, IOS. Different versions of that operating system support different feature sets and thus different command syntaxes. Instead of programming a complete interface for each version of IOS, you can use _ _call() to automatically handle command dispatching. Because the router must be accessed via Telnet, you can extend PEAR's Net_Telnet class to provide that layer of access. Because the Telnet details are handled by the parent class, you only need two real functions in the class. The first, login(), handles the special case of login. login() looks for the password prompt and sends your login credentials when it sees the password prompt.
The second function you need in the Net_Telnet class is the _ _call() handler. This is where you take care of a couple details:
Here is the implementation of Cisco_RPC; note how short it is, even though it supports the full IOS command set: require_once "Net/Telnet.php";
class Cisco_RPC extends Net_Telnet {
protected $password;
function _ _construct($address, $password,$prompt=
You can use Cisco_RPC quite easily. Here is a script that logs in to a router at the IP address 10.0.0.1 and prints that router's routing table: $router = new Cisco_RPC("10.0.0.1", "password");
$router->login();
print $router->show("ip route");
|