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

    • carbonara72: Hi, This is a brilliant feature! I discovered LastBrigde.net a couple of days ago and was frustrated...
    • fernyb: @mike_rofone, I will kill your account, just a side note, I know it’s missing a feature to reset...
    • mike_rofone: Hey Dude, awesome work, it it’s set up it just works like a charm. Maybe I’m dumb but I...
    • mjm: Send me an invite? Thanx., mjm.ent -at- gmail
    • Steven Luscher: Awesome! Now what I’d really like is a way to scrobble tracks played on my SoundBridge…

    Recent Listened to Tracks

    Loading...


My blog is worth $1,693.62.
How much is your blog worth?


Bad Behavior has blocked 208 access attempts in the last 7 days.

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