美文网首页
使用魔术方法(__call或__callStatic)ZendS

使用魔术方法(__call或__callStatic)ZendS

作者: 为啥这么有钱 | 来源:发表于2019-04-03 18:49 被阅读0次

举例说明:

/**
     * 调用不可见的静态方法
     * @static
     * @param string $func
     * @param array $arg
     * @return DB
     */
    public static function __callStatic(string $func, array $arg):DB
    {
        $arg[0] = $arg[0] ?? 'read';
        self::$dbName = $func.'_'.$arg[0];

        if (self::$pdo[self::$dbName] == null) {
            $config = self::loadConfig(self::$dbName);
            try {
                $dsn = "mysql:host={$config['host']};dbname={$config['database']}";
                self::$pdo[self::$dbName] = new self($dsn, $config['username'], $config['password']);
                self::$pdo[self::$dbName]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $e) {
                throw new Exception($e->getMessage());
            }
        }

        return self::$pdo[self::$dbName];
    }

上边是定义了一个静态类,在静态类中定义了一个__callStatic()魔术方法来调用不可见或者说不存在的静态类成员方法, 在脚本中使用className:: 时zendstudio只能提示__callStatic(), 不会提示该类支持的方法,
这时我们可以给类添加注释 , 如下

* @method static DB product(string $arg)  $arg取值为read&write 默认为read

上边注释是说明该方法是类的一个静态方法, 如果声明非静态去掉static关键字即可


120805-20190403174845654-994935932.png

相关文章

网友评论

      本文标题:使用魔术方法(__call或__callStatic)ZendS

      本文链接:https://www.haomeiwen.com/subject/snftiqtx.html