Answer the question
In order to leave comments, you need to log in
How can I force the current object to overwrite itself?
Added tags Java
and C++
, because I wonder if something similar is possible in other OOP languages.
Such a class:
<?php
class DB {
private $link;
private $config;
private $charset;
function __construct($config, $charset) {
# линки
$link = &$this->link;
# сохранение аргументов
$this->config = $config;
$this->charset = $charset;
# подключение к СУБД
$link = new mysqli($config['host'], $config['username'], $config['password']);
# установка БД
$this->SetDB($config['dbname']);
# установка кодировки
$this->SetCharset($charset);
}
function SetDB($dbname) {
# ...
}
function SetCharset($charset) {
# ...
}
function Reconnect() {
# линки
$config = &$this->config;
$charset = &$this->charset;
# перезапись объекта
$this = new self($config, $charset);
}
# ...
}
$db = new DB($MySQLConfig, $charset);
# ...
$db->Reconnect();
PHP Fatal error: Cannot re-assign $this in /class/DB.php
$db = $db->Reconnect();
function Reconnect() {
# линки
$config = &$this->config;
$charset = &$this->charset;
# перезапись объекта
$this->__construct($config, $charset);
}
Answer the question
In order to leave comments, you need to log in
In telepathy mode, I guess what you want to implement. Apparently, we are talking about a completely standard mechanism for generating a connection object from a database object.
To understand how such bicycles are built, look into the code of any ORM or, in general, any OOP wrapper over a database driver. In most cases, you will see the following picture:
1. The database configuration is a factory (yes, yes, the very patterns that neophytes NEED ).
2. The method connect
returns a connection object.
3. The connection object (except for query execution methods) has a method close
that closes the connection (an attempt to execute a query on a closed connection will generate an error).
4. The connection (as an object) lives once and cannot be reopened after being closed. But you can always open a new connection from the database factory.
Why so:
The main principle of OOP: a separate concept - a separate class. The database (on the client side) is only a configuration: server address, username, password, database name and other parameters. A database connection is a separate entity through which transactions are created and cursors (separate entities) through which queries are executed. The result of query execution is a separate entity. A single row in a selection is a single entity (unless it's a tuple). And only individual fields in a row have primitive data types.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question