PHP Snippet

Posted in PHP, Programming on Mar 08, 2008

Here is a PHP Snippet I wrote. It’s a cool trick to for calling multiple methods in a much simpler way. Inspired by Ruby’s ActiveRecord.

<?php

interface Member {
	function login($username, $password);
	function update($status);
}

class Base implements Member {
	public function login($username, $password) {
		echo "You will be logged in as: {$username} with Password: {$password}\n";
	}
	
	public function update($status) {
		echo "Your New Status Message is: {$status}\n";
	}
	
	public function __call($method, array $argv) {
		if(preg_match('/^do_*/i', $method)) {
			foreach(explode("_and_", substr($method, 3)) as $k => $v) {
				$param = array();
				foreach($argv[$k] as $value) { $param[] = "'{$value}'"; }
				$param = join(", ", $param);
				$code = '$this->'. $v ."({$param});";
				eval($code);
			}
		}
	}
}


class User extends Base {
	
	public function say_hello($message) {
		echo "Message: {$message} \n";
	}
}


$usr =& new User();

$usr->do_login_and_update(array("username", "password"), array("Hello World"));
# Prints the following:
# You will be logged in as: username with Password: password
# Your New Status Message is: Hello World
#

$usr->do_login_and_say_hello(array("username", "password"), array("Hi how are you?"));
# Prints the following:
# You will be logged in as: username with Password: password
# Message: Hi how are you?
#

$usr->do_login_and_update_and_say_hello(array("username", "password"), array("Hello World"), array("Hi how are you?"));
# Prints the following:
# You will be logged in as: username with Password: password
# Your New Status Message is: Hello World
# Message: Hi how are you?
#

?>

Trackback URI | Comments RSS

Leave a Reply

  • Recent Comments


eastern-avalanche
eastern-avalanche
eastern-avalanche
eastern-avalanche