0
由于我正在处理一段需要装饰器模式的代码,因此我想通过处理__call魔法方法使其非常简单。事实上,当我使用装饰器模式(这里,添加一个单例,添加一些方法并禁止其他一些方法)时,一些方法不需要被重写。所以使用__call是简化代码的好方法。当我使用__call时,如何通过引用传递参数
当某些方法需要通过引用传递的参数时,会引发我的情况。
举个例子,我创建了一个XPDO类来减少PDO。这不是我以前的情况,但我不能证明这一点。
<?php
class XPDO{
private static $dbInstance=null;
private $pdoConnexion;
static function getInstance(){
if(self::$dbInstance ==null){
self::$dbInstance = new XPDO(/*tes params*/);
}
return self::$dbInstance;
}
private function __clone(){
}
private function __construct(){
$this->pdoConnexion = new PDO('mysql:localhost;dbname=blog','root','');
}
/**
*on possède toutes les méthodes de PDO mais en plus certaines qui nous sont propres ou qui
*surchargent/limitent celles de PDO si telles qu'elles sont implémentées dans PDO, on ne les aime pas.
*/
public function __call($method, $args){
if(is_callable(array($this,$method))){
return call_user_func_array(array($this,$method),$args);
}else if(is_callable(array($this->pdoConnexion,$method))){
return call_user_func_array(array($this->pdoConnexion,$method),$args);
}
}
/**
*
*@param string $query the query we want to add the where
*@param string $param name of the column
*@return string the identifier that we would use to bind a value
*/
private function addAndWhere(&$query,$param){
$uid = rand(1,100000);
if(strpos($query,'WHERE')){
$query.= ' AND '.$param.'=:'.$param.$uid;
}else{
$query.= ' WHERE '.$param.'=:'.$param.$uid;
}
return $param.$uid;
}
}
$pdo = XPDO::getInstance();
$query = 'SELECT * FROM sometable';
var_dump($pdo->addAndWhere($query,'smth'));
var_dump($query);
因为addAndWhere需要一个基准和一个副本是有这个会失败。 此代码可以通过将addAndWhere传递给public来轻松修复,并且它有道理。这里只是一个例子。现在想象一下,这是需要参考的PDO,并且你明白了我的观点。
好的,谢谢您的确认。我知道我现在必须做什么。 – artragis 2012-04-09 07:45:06