0
Quick question: how to recover the instance of an object created in a different file in a PHP application?
Full question: I am creating a project for PHP studies where I have the file conn.php
which contains the PDO instance for the database connection. Another file called functions.php
contains the function getAllUsers()
that should perform the query in the database and return the results.
Using only the require('conn/conn.php')
would not recover the instance of the object created in the file? If not, how could it achieve this?
Thank you in advance for all your attention!
The code of the archives conn.php
and functions.php
follow below:
Conn.php
<?php
/*
** Arquivo de conexão com o banco de dados
** Quaisquer alterão irá impactar na aplicação inteira
*/
require('config.php');
// Função de conexão com o banco de dados
function databaseStartConnection() {
$dsn = DBBRAND . ":dbname=" . DBNAME . ";host=" . DBHOST;
// Tente se conectar ao banco com as crendenciais fornecidas
try {
$pdo = new PDO($dsn, DBUSER, DBPASS);
} catch (PDOException $e) {
// Em caso de erro, exiba a mensagem e encerre a aplicação
echo "<p><b>Erro de conexão com o banco de dados: </b>" . $e->getMessage() . "</p><br>";
die();
}
}
functions.php
<?php
/*
** Realiza consulta teste
** Modificar este arquivo para a consulta real
*/
require('conn/conn.php');
// Inicia conexão com o banco de dados
databaseStartConnection();
// Recupera do banco todos os usuários
function getAllUsers($pdo = $this->$pdo) { // Recuperar o objeto criado no arquivo conn.php
// Consulta vai aqui
}
// Fecha conexão com o banco de dados
databaseCloseConnection();
PHP OO is rarely a good thing. PHP is almost always used in situations where there is no state preservation, and OO is directly linked to state maintenance. It has a way of serializing and deserializing objects, but it’s usually even worse. However, in your given example, you have no reason to use any OO. Even though unfortunately something forces you to use PDO, reconnecting to each script is what is normally done. And the fact of using OO syntax does not prevent thinking procedurally.
– Bacco
Got it. But anyway I would like to keep my query functions in the bank within the file
functions.php
and my connection within theconn.php
. I cannot think at this point another viable way to do this. Doing everything within the same file would be very disorganized.– Edinaldo Ribeiro
Yes, it’s convenient to keep it that way, but note that this has nothing to do with needing the first instance created. The fact that you use a "new" does not mean that you should cling to that instance. Each time something includes that script, an instance will be created and discarded at the end.
– Bacco
Right, within my function
getAllUsers()
I would not need to have established the connection with my bank, with the credentials passed inside my fileconn.php
? Or would I need to create a new connection for each function I create? I don’t think that would be very practical.– Edinaldo Ribeiro
Very calm at this time kkkk. Note that we are not talking about OO anymore. The normal PHP when used in quick scripts (web pages) is to open the connection 1 time only at the beginning of the script, store in a variable, and use during the life of the script. If it will be in the script itself or if it will be included at the beginning, it is a matter of code organization. Usually a require_once is made at the beginning for this. Again, this is independent of the paradigm you’re going to use. Be a
$var = new PDO(...);
or$var = mysqli_connect(...);
the idea is the same, do 1x at the beginning and use the variable during the script.– Bacco
The fact that it is an object instance or pointer to a connection is detail, considering the very short life time of the script.
– Bacco
@Bacco I managed to solve using a
return
in my variable$pdo
and recovering the instance in the filefunctions.php
assigning to a new variable the value of thisreturn
. I will edit my question with the new code if you want to take a look. The problem is that now I can’t call the functiongetAllUsers()
in my view without having to pass a parameter.. I will think about how I will resolve this yet, but thank you very much for your attention.– Edinaldo Ribeiro