PHP class vs function

3

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.

    
asked by anonymous 24.10.2016 / 23:50

1 answer

7

The main feature of object orientation is to join or join, the data structure (usually a type defined by the programmer) class, with behaviors (methods). Some languages force this as for example java, where it is not possible to define a method / function without owner (class), php allows to mix classes / object with functions which can be an advantage in some cases.

Advantages of using classes :

  • Easily group and share elements (properties) between methods.

  • Methods can save the state of the object.

  • Provides an intermediate scope between global and local variables, compared to functions and structured code.

Advantages of using functions :

  • The call of a function has its atomic execution, ie the action is performed or not, usually does not have / guard status, which is good for codes where there are concurrent accesses, since they do not have to deal with synchronizations.
25.10.2016 / 00:23