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

    • tory burch canvas tote: Incredible, I actually better begin saving this money. Really like a lot of these kind of...
    • Kostenloser Stromanbieter Vergleich online: A truly gripping article. I leave maintain to supervise it.
    • a4928971: I’ve said that least 4928971 times. SCK was here
    • Jennifer Youns: Many thanks to you for sharing these kind of wonderful content. In addition, the optimal travel plus...
    • Alonzo Williams: Thanks for your write-up on the travel industry. We would also like to add that if you’re a...

    Recent Listened to Tracks

    Loading...

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

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