首页 > PHP > PHP中的__call(),__set()和__get()

PHP中的__call(),__set()和__get()

2009年2月23日

利用__call()在php中实现重载

<?php
class Test {
	public function __call($fun, $args) {
		if (method_exists($this, $fun.count($args))) {
			return call_user_func_array(array(&$this, $fun.count($args)), $args);
		}
		else {
			throw new Exception('调用了未知方法:'.get_class($this).'->'.$fun);
		}
	}
 
    //一个参数的方法
	public function foo1($a) {
			echo "你在调用一个参数的方法,参数为:".$a;
	}
    //两个参数的方法
	public function foo2($a, $b) {
			echo "你在调用两个参数的方法,参数为:".$a."和".$b;
	}
}
 
$test = new Test();
$test->foo("a");
$test->foo("a", "b");
$test->foo("a", "b", "c");
?>

执行结果如下:
你在调用一个参数的方法,参数为:a
你在调用两个参数的方法,参数为:a和b

Fatal error: Uncaught exception ‘Exception’ with message ‘调用了未知方法:Test->foo’…

再来看看神奇的__set()和__get()

<?php
class Test {
	private $_vars = array();
 
	public function __set($k, $v) {
		$this->_vars[$k] = $this->validate($v);
	}
 
	public function __get($k) {
		return isset($this->_vars[$k]) ? $this->_vars[$k] : null;	
	}
 
	private function validate($v) {
		return htmlspecialchars(addslashes($v));
	}
}
 
$test = new Test();
$test->foo = "哈哈";
$test->bar = "嘿嘿";
echo $test->foo;
echo $test->bar;
?>

“)

admin PHP

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.