因为我正在编写一段需要装饰器模式的代码,所以我想通过处理__call魔术方法来使其使用起来非常简单。
事实上,当我使用装饰器模式(在这里,添加一个单例,添加一些方法,禁止其他一些方法)时,一些方法不需要被覆盖。因此,使用__call是简化代码的好方法。
当一些方法需要通过引用传递参数时,我的情况就会出现。
举个例子,我创建了一个解码PDO的XPDO类。这不是我以前的案子,但我不能展示那个。
<?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,你明白我的意思了。
发布于 2012-04-09 06:48:16
来自php手册中的重载页面
这些魔术方法的参数都不能通过引用传递。
没有干净的解决方案。
你只能这样做
$pdo->addAndWhere(&$query,'smth');但这是从5.3开始就被弃用的,带有相对警告。
https://stackoverflow.com/questions/10061621
复制相似问题