Sobes.tech
Middle
200

What are old-style and new-style classes, and what is the difference between them?

Answer from AI

sobes.tech AI

Coupling in PHP refers to the degree to which modules or components depend on each other. Low coupling is considered good practice because it makes the code more flexible, understandable, and easier to test and maintain.

Different types of coupling (from worst to best):

  • Content coupling: One module modifies the internal data of another.
  • Common coupling: Modules use shared global data.
  • External coupling: Modules depend on external data formats, protocols, or devices.
  • Control coupling: One module passes a control flag to another to influence its logic.
  • Data coupling: Modules interact only through primitive data types. Stamp coupling: Passing entire data structures, but only part is used.

In PHP, coupling often manifests through:

  • Direct method or function calls: One class directly calls another.

    <?php
    class A {
        public function doSomething() { /* ... */ }
    }
    
    class B {
        public function process() {
            $a = new A();
            $a->doSomething(); // Direct call, creates coupling
        }
    }
    
  • Inheritance: Child class tightly bound to parent.

  • Global variables or singletons: Creates shared coupling.

Reducing coupling is achieved through:

  • Dependency Injection (DI): Passing dependencies via constructor, setter, or method.

    <?php
    class A {
        public function doSomething() { /* ... */ }
    }
    
    class B {
        private A $a;
    
        public function __construct(A $a) { // DI via constructor
            $this->a = $a;
        }
    
        public function process() {
            $this->a->doSomething(); // Using injected dependency
        }
    }
    
    // Usage
    $a_instance = new A();
    $b_instance = new B($a_instance);
    $b_instance->process();
    
  • Interfaces and abstract classes: Modules depend on abstractions, not on concrete implementations.

  • Design patterns: E.g., Observer, Strategy, Factory.

  • API agreements: Well-defined interfaces between modules.

  • Encapsulation: Hiding internal implementation.

Low coupling leads to more modular, maintainable, and testable applications in PHP.