PHP Classes, why are they better

How is OOP better than normal functions with $GLOBALS[] globals? For me, this is how the code becomes more:

  1. + variables only work within one class
  2. – long class initialization (load increases by 10% when class is called)
  3. – it’s not clear how include works
  4. is it possible to create a variable inside one class and get it inside another class, or is it possible to use constants or global variables?

Answer 1, authority 100%

The question is not correctly posed. Classes/Objects != OOP(did you mean OOP? Because at the request of OPP Google returnsthe website of the Society for Psychoanalytic Psychotherapy)

OOPis a paradigm based on three pillars: inheritance, polymorphism, encapsulation. Classes/objects are essentially just a means to implement this paradigm.

More about OOPand procedural programmingyou can read, for example, in wikipedia.


Answer 2, authority 100%

Classes and their objects are a convenient way to make large and scalable projects.

For example: in the “car” project, in order to use the “car radio” object, it is not necessary to know the basics of radio signals, just run the “enable” public method. The implementation of the “car radio” class is in one place (module), and the logic of the “car” project, where this object is used, is in another.

Flies separately, compote separately.


Answer 3, authority 100%

Pros of using classes:

  1. ease of use by third-party programmers
    That is, you write a class, compile its documentation, and pass it on to a third-party developer. At the same time, it does not matter at all what happens inside the class. It only knows what class methods have as inputs and outputs.

  2. easier extension
    It is inheritance, it is polyformism. That is, it is possible to combine the functionality of several classes in one or change the functionality of a class without changing its interface.

  3. close code (relative)
    It is possible to set the variables and methods of the class so that they are not accessible from the outside.

  4. classes clutter up namespaces less
    There is one instance of the class – and that’s it. All variables are inside it.

Cons:

  1. yes, work through classes is slower than through functions