PHP:Pass Method/Function 传递方法

需求: 需要外部提供Function以进行操作

解决方案: 外部传递Function Name到目标页面/类中, 然后使用call_user_func()方法使用外部方法.

代码举例:

1. 方法提供页面:

/**
 * 打印log信息.
 * @param $mesg
 * @return unknown_type
 */
function logMesg($mesg) {
	echo $mesg;
	flush();
}

$insprMail->setLogFunc("logMesg"); // 传递log打印方法.

2. 目标类/页面中使用方法:

	/** 日志写入方法. */
	public $logFunc;

	/**
	 * 设定Log打印方法.
	 * @param $logFunc
	 * @return unknown_type
	 */
	function setLogFunc($logFunc) {
		$this->logFunc = $logFunc;
	}

	/** 打印log信息. */
	protected function printLog($mesg) {
		call_user_func($this->logFunc, $mesg); // 使用外部传递近来的方法打印log信息
	}
This entry was posted in PHP and tagged , , . Bookmark the permalink.

One Response to PHP:Pass Method/Function 传递方法

  1. 小邪 says:

    抢滩登陆沙发 ~

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>