使用 $this 调用类内的函数


Call function inside class with $this

User::updatemain($set, $where); 

这会产生致命错误:不在对象上下文中使用$this我的用户类从 Dbase 类扩展而来,这里是用户类函数:

public static function activate($set, $where) {
    return $this->updatemain($set, $where);

这是 dbase 类(某些部分):

private function query($sql = null, $params = null) {
    if (!empty($sql)) {
        $this->_last_statement = $sql;
        if ($this->_db_object == null) {
            $this->connect();
        }
        try {
            $statement = $this->_db_object->prepare($sql, $this->_driver_options);
            $params = Helper::makeArray($params);
                $x = 1;
                if (count($params)) {
                    foreach ($params as $param) {
                        $statement->bindValue($x, $param);
                        $x++;
                    }
                }
            if (!$statement->execute() || $statement->errorCode() != '0000') {
                $error = $statement->errorInfo();
                throw new PDOException("Database error {$error[0]} : {$error[2]}, driver error code is {$error[1]}");
                exit;
            }
            //echo $sql;
            return $statement;
        } catch (PDOException $e) {
            echo $this->formatException($e);
            exit;
        }
    }
}
public function updatemain($set, $where) {
    return $this->query($sql, $params);
}

这是Dbase类的一部分

您正在调用静态方法,因此在该上下文中没有$this

如果你想从给定的类调用其他静态方法,那么使用self::method()但如果你想调用非静态方法,你就有问题了。首先,您必须创建新对象。

使用静态方法时,不能在内部使用 $this

public static function activate($set, $where) {
       return self::updatemain($set, $where);
}

或者你必须使用辛格尔顿设计

编辑

最佳解决方案 - 将类重写为对数据库对象的单点访问。并创建模型类以进行数据库访问。请参阅下面的示例代码:

核心

应用核心

<?php
class AppCore
{
    public static $config  = array();
    public static $ormInit = false;
    public static function init($config)
    {
        self::$config = array_merge(self::$config, $config);
    }
    public static function db($table)
    {
        // ORM - see http://idiorm.readthedocs.org/en/latest
        if (!self::$ormInit) {
            ORM::configure(self::$config['db']['connection']);
            ORM::configure('username', self::$config['db']['username']);
            ORM::configure('password', self::$config['db']['password']);
            self::$ormInit = true;
        }
        return ORM::for_table($table);
    }
}

用户模型

<?php
class UserModel
{
    const TABLE = 'user';
    public static function findById($u_id)
    {
        $result = AppCore::db(self::TABLE)->where('u_id', $u_id)->find_one();
        return $result ? $result->as_array() : null;
    }
}

应用核心初始化部分

AppCore::init(array(
    'db' => array(
        'connection' => "mysql:dbname={$db};host={$host}",
        'username' => $user,
        'password' => $pass
    ),
));

我希望它有助于使您的代码更好