开发者

How to overload methods with variable number of arguments?

I have a class that holds a mysqli instance (this to avoid spreading database settings all over the source code).

The class DB looks like:

class DB {
    private $mysqli;

    public function connect() {
        $this->mysqli = new mysqli("localhost", "user", "pwd", "db-name");
    }

    public function __call($method, $args) {
        return $this->mysqli->$method(extract($args));
    }
}

As you might see what I'm trying to do is to overload every method call executing the m开发者_运维问答ysqli ones.

In the other php file I have:

$unq_vstr = $this->db->query("SELECT * FROM user_log WHERE user_ip='$ip' AND user_last_visit='$now';");
if ($unq_vstr->num_rows > 0) { // ERROR
    // ...
}

But I'm getting "Notice: Trying to get property of non-object in /home/alessandro/www/admin/index.php on line 25" corresponding to the if statement ($unq_vstr->num_rows).

What am I doing wrong? I'm pretty sure it might depend on the DB class, but I can't figure out what the problem is.

Do you think I should use an alternative way to do it (without wrap mysqli inside my own class)? Any suggestion is appreciated.


You are looking for

  • call_user_func_array — Call a user function given with an array of parameters

Example:

public function __call($method, $args) {
    return call_user_func_array(
        array($this->mysqli, $method), 
        $args
    );
}

See the chapter on Pseudo-types and variables for possible callback syntax

On a sidenote, wrapping the mysqli instance into a Decorator that doesnt decorate any of the method calls is rather pointless. So, yes, I do think you should not wrap the mysqli object into the Decorator. Instead, create the mysqli instance once in bootstrap and then pass it to any component that needs it from there, stacking objects from the inside out.

Also see

  • php application global settings and
  • Dependency Hell — how does one pass dependencies to deeply nested objects?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜