php5 OOP – Function Overloading

PHP

PHP

Starting php4, object oriented concepts have been made available to the programmer. Though not well developed, they paved the way for a more complete implementation of the OOP basics in the php5 version. However, one thing that remains lacking is the ability ot overload the functions.

Overloading of functions is quite an useful feature. In the simplest form, it gives you the freedom to declare a class with more than one constructors.

Not to get disheartened though, we have a simple enough way to work around this short coming. In php, when a call is made to a function that does not exist, then the control searches for the __call() function. We make use of this to carve out the over loading feature that we need.

Below, I am writing the code for a Register class which has two variables – name and pass. The constructor is being overloaded here.

class Register {
private $name;
private $pass;

public function Register() {
$num = func_num_args();
$args = func_get_args();

$funcName = 'Register'.$num;
$this->__call($funcName, $args);
}

private function Register0() {
$this->name = '';
$this->pass = '';
}

private function Register2($name, $pass) {
$this->name = $name;
$this->pass = $pass;
}

public function __call($funcName, $args) {
$this->call_user_func_array(array($this, $funcName), $args);
}

public function setName($name) {
$this->name = $name;
}

public function setPass($pass) {
$this->pass = $pass;
}
} // Register

// regA is using the Register2() constructor
$regA = new Register('Anu', '@#$#@$@$');

// regB is using the Register0() contructor
// and subsequently setting the values of name, pass
$regB = new Register();
$regB->setName('Anu');
$regB->setPass('@#$#@$@$');
Reblog this post [with Zemanta]

Popularity: 2% [?]

Related posts:

  1. Partition Function
  2. Project Euler : Quadratic Producing Longest Prime Sequence
  3. A Logger In C
  4. php – Sessions
  5. Variadic Functions