When and why should I use a class
instead of a simple function
in PHP?
For example, I have a function that performs the insertion of a history in the database, which is a common function to many others.
functions.php
<?php
function insereHistorico($idUsuario, $descricao) {
$sql = "INSERT INTO historico (id, descricao) VALUES ($idUsuario, $descricao)";
}
file.php
<?php
function adicionaUsuario() {
//Executa todo o processo aqui
//...
//Insere no log
insereHistorico($idUsuario);
}
But I also know that the same function could be a class, like this:
functions.php
<?php
class FuncaoClass {
public function insereHistorico($idUsuario, $descricao) {
$sql = "INSERT INTO historico (id, descricao) VALUES ($idUsuario, $descricao)";
}
}
file.php
<?php
function adicionaUsuario() {
//Executa todo o processo aqui
//...
//Insere no log
$funcao = new FuncaoClass;
$funcao->insereHistorico($idUsuario, $descricao);
}
What seems to me to be an advantage in using a class is having a more organized code, but since I'm not an advanced user in PHP, I do not know what the main differences or considerations are about this comparison.
Just to give context, I use PHP to manage the WebSites / WebApps backend, where I use AngularJS to call these functions and manage the database. Usually functions similar to the arquivo.php
example return me data (list of users, news, requests, etc.) whereas functions like the example of the funções.php
file serve to do some common management of multiple functions.