PHP-不在对象上下文中时使用$this


PHP - Using $this when not in object context

当我尝试从继承的类执行此代码时,我得到了以下错误Using $this when not in object context这是我的代码

abstract class Connection {
    private static $host;
    private static $username;
    private static $password;
    private static $database;
    public function __construct() {
        self::$host = 'localhost'; // database server address
        self::$username = 'root'; //database server username;
        self::$password = ''; //database server password;
        self::$database = 'oms'; //database name
    }
    private function connect() {
        return new PDO('mysql:host=' . Connection::$host . ';dbname=' . Connection::$database . '', Connection::$username, Connection::$password);
    }
    protected function execute($sql) {
        $this->connect();
        return $this->connect()->query($sql);
    }
}

这是什么原因?我在Connection类中没有使用任何静态方法。So为什么给出这个错误?

这可能就是您想要的:

abstract class Connection {
    protected static $host;
    protected static $username;
    protected static $password;
    protected static $database;
    protected static $connection;
    public static function load() {
        self::$host = 'localhost'; // database server address
        self::$username = 'root'; //database server username;
        self::$password = ''; //database server password;
        self::$database = 'oms'; //database name
    }
    protected static function connect() {
        // Only create the connection once
        if (!self::$connection) {
            self::$connection = new PDO('mysql:host=' . self::$host . ';dbname=' . self::$database . '', self::$username, self::$password);
        }
        return self::$connection;
    }
    public static function execute($sql) {
        return self::$connect()->query($sql);
    }
}
// Because we can't use an abstract class
class ConcreteConnection extends Connection {}
// Execute a SQL call
ConcreteConnection::execute("SELECT * FROM `table`");

但你会有一个辛格尔顿模式,这对以后的测试和改变来说是一种痛苦。我建议你这样做:

abstract class Connection {
    protected $host;
    protected $username;
    protected $password;
    protected $database;
    protected $connection;
    public function _construct($host, $username, $password, $database) {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
        $this->database = $database;
    }
    protected function connect() {
        if (!$this->connection) {
            $this->connection = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->username, $this->password);
        }
        return $this->connection;
    }
    public function execute($sql) {
        return $this->connect()->query($sql);
    }
}
// Because we can't use an abstract class
class ConcreteConnection extends Connection {}
// Inject our parameters into our class
$connection = new ConcreteConnection('host', 'username', 'password', 'database');
// Execute a SQL call
$connection->execute("SELECT * FROM `table`");