PHP class vs Function

Asked

Viewed 829 times

3

When and why should I wear one class instead of a function simple in PHP?

For example, I have a function that performs the insertion of a history in the database, which is a function common to many others.


php functions.

<?php
function insereHistorico($idUsuario, $descricao) {
    $sql = "INSERT INTO historico (id, descricao) VALUES ($idUsuario, $descricao)";
}

php file.

<?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, this way:

php functions.

<?php
class FuncaoClass {

    public function insereHistorico($idUsuario, $descricao) {
        $sql = "INSERT INTO historico (id, descricao) VALUES ($idUsuario, $descricao)";
    }
}

php file.

<?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 the use of class is to have a more organized code, but as I am not an advanced user in PHP, I do not know what are the main differences or considered regarding this comparative.

Just to give the context, I use PHP to manage the backend of Websites/Webapps, where I use Angularjs to call these functions and manage the database. Normally functions similar to the example of arquivo.php return data (user list, news, requests, etc.) while functions such as the file example funções.php serve to do some management common to multiple functions.

1 answer

7


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

Advantages of using classes:

  • Allows simple grouping and sharing 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 function:

  • The call of a function has its atomic execution or whether the action is performed or not, usually does not have/guard state, which is good for codes where it has concurrent accesses because they do not have to deal with synchronizations.
  • But then using one or the other, or even using both in the same project would have no direct impact, right? It would be more related to a code structure than to a "better method" between one or the other. Of course, without taking into account the small details, like the one you mentioned, for example Métodos podem guardar o estado do objeto.

  • @Celsomtrindade this same question of structure, when choosing one or the other can ask: do I need to save state? does it bring any benefit? having an intermediate (variable) scope brings some benefit? is it desirable? A strange situation is when vc has an object and most methods ask for arguments and return some value but does not store state (for some reason) this is a good reason to target the class, would not using functions be better and pq? continue the class pq? ... continue.

  • 1

    Another and easier to detect are those generic classes (practically a repository of functions) that do everything or lack cohesion, a class should only have a liability (solve a type of problem) and their methods should make sense in context. In php it is possible to group functions by namespace.

  • I understood. Today, in the current state of my application, I have no case that is necessary to save state, all functions perform some process and return a value. For example, create a link from an id and a variable, so they could all be just functions. What I liked about class use is to have a clearer view of where that function is being called, because it would have something like this: ClientClass::carregaCliente(), for example.

  • @rray is there any difference in security (since it works as a encapsulation, correct me if I’m wrong)? And performance (creating a class should generate more resource expenditures than just creating variables/functions)? And what would be "save state"?

  • 1

    @Guilhermecostamilam believe not. There must be some difference but it should be small in the case of PHP this type of optimization does not have many gains. When you call a method you can work with the attributes of the class/object (pick up/manipulate its current or already accumulated values) and after that the assignees will still exist and have values. Already after the call of a function all its local variables will be destroyed.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.