0

当我正在编写一段需要装饰器模式的代码时,我想通过处理 __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 需要参考,你明白了我的意思。

4

1 回答 1

1

来自重载页面中的 php 手册

这些魔术方法的任何参数都不能通过引用传递。

没有干净的解决方案。

你只能做

$pdo->addAndWhere(&$query,'smth');

但这是自 5.3 以来已弃用,并带有相对警告。

于 2012-04-08T22:48:16.117 回答