← PHP EspañolChapter 08 of 13

Programación Orientada a Objetos

## Objetivos de Aprendizaje - Comprender clases y objetos - Dominar encapsulamiento y visibilidad - Trabajar con herencia - Aprender interfaces y traits - Comprender namespacing ## Clases y Objetos ### Definición de Clase ```php name = $name; $this->age = $age; } // Methods public function greet(): string { return "Hello, my name is " . $this->name; } } ?> ``` ### Creando Objetos ```php greet(); // Hello, my name is Alice echo $person1->name; // Alice ?> ``` ## Propiedades ### Declaración de Propiedades ```php ``` ### Propiedades Tipadas (PHP 7.4+) ```php ``` ## Visibilidad (Modificadores de Acceso) ### Public ```php name = "Alice"; // OK ?> ``` ### Protected ```php ssn = $ssn; // OK - within same class hierarchy } } $person = new Person(); $person->ssn = "123-45-6789"; // Error! ?> ``` ### Private ```php secret; // OK - within same class } } $person = new Person(); echo $person->secret; // Error! echo $person->reveal(); // "hidden" ?> ``` ## Métodos ### Definición de Métodos ```php ``` ### Palabra Clave $this ```php name = $name; // $this refers to the current object } public function getName(): string { return $this->name; } } ?> ``` ## Constructores y Destructores ### Constructor ```php name = $name; $this->age = $age; } } $person = new Person("Alice", 25); $default = new Person("Bob"); // age defaults to 0 ?> ``` ### Promoción de Propiedades del Constructor (PHP 8) ```php name; // Alice echo $person->age; // 25 ?> ``` ### Destructor ```php connection = connect($host); } public function __destruct() { close($this->connection); // Cleanup when object is destroyed } } ?> ``` ## Herencia ### Palabra Clave extends ```php name = $name; } public function speak(): string { return "..."; } } class Dog extends Animal { public function speak(): string { return "Woof!"; } public function fetch(): string { return "$this->name fetches the ball"; } } $dog = new Dog("Buddy"); echo $dog->speak(); // Woof! echo $dog->fetch(); // Buddy fetches the ball ?> ``` ### Palabra Clave parent ```php name = $name; $this->age = $age; } } class Employee extends Person { private string $position; public function __construct( string $name, int $age, string $position ) { parent::__construct($name, $age); // Call parent constructor $this->position = $position; } } ?> ``` ## Clases Abstractas ### Definición ```php area(); } } ?> ``` ### Implementación ```php radius = $radius; } public function area(): float { return pi() * $this->radius ** 2; } public function perimeter(): float { return 2 * pi() * $this->radius; } } class Rectangle extends Shape { private float $width; private float $height; public function __construct(float $width, float $height) { $this->width = $width; $this->height = $height; } public function area(): float { return $this->width * $this->height; } public function perimeter(): float { return 2 * ($this->width + $this->height); } } ?> ``` ## Interfaces ### Definición de Interfaz ```php ``` ### Implementación de Interfaz ```php balance += $amount; return true; } public function refund(float $amount): bool { if ($amount > $this->balance) { return false; } $this->balance -= $amount; return true; } public function getBalance(): float { return $this->balance; } } class PayPalGateway implements PaymentGateway { // ... implements all methods } ?> ``` ### Múltiples Interfaces ```php ``` ### Herencia de Interfaces ```php ``` ## Traits ### Trait Básico ```php logs[] = date("Y-m-d H:i:s") . ": $message"; } public function getLogs(): array { return $this->logs; } } ?> ``` ### Usando Traits ```php name = $name; $this->log("User created: $name"); } } $user = new User("Alice"); echo $user->getLogs()[0]; // 2024-01-01 12:00:00: User created: Alice ?> ``` ### Múltiples Traits ```php createdAt = time(); } } trait Validateable { public function validate(): bool { // validation logic return true; } } class Entity { use Timestamp, Validateable; } ?> ``` ### Resolución de Conflictos ```php hello(); // B echo $obj->hi(); // A ?> ``` ### Anulación de Propiedades de Trait ```php createdAt = time(); } } class Entity { use Timestamped; public function __construct() { $this->setTimestamp(); } } ?> ``` ## Miembros Estáticos ### Propiedades Estáticas ```php ``` ### Métodos Estáticos ```php ``` ### Late Static Binding ```php ``` ## Constantes ### Constantes de Clase ```php ``` ### Constantes de Interfaz ```php ``` ## Verificación de Tipos ### instanceof ```php ``` ### Resolución de Nombre de Clase ```php ``` ## Comparación de Objetos ```php ``` ## Namespaces ### Declaración ```php ``` ### Usando Namespaces ```php ``` ### Declaración use ```php ``` ### Aliases ```php ``` ### Namespace Global ```php input); // Global trim() } } ?> ``` ## Autoloading ### spl_autoload_register ```php ``` ### PSR-4 con Composer ```json { "autoload": { "psr-4": { "App\\": "src/", "Tests\\": "tests/" } } } ``` ## Resumen - Clases: `class Name { }` - Objetos: `new ClassName()` - Visibilidad: `public`, `protected`, `private` - Constructor: `__construct()` - Herencia: `class Child extends Parent` - Abstracto: `abstract class` y `abstract method` - Interfaces: `interface` e `implements` - Traits: `trait Name` y `use TraitName` - Estático: `static $property` y `static method()` - Constantes: `const NAME = value` - Namespaces: `namespace App\Models;` - Autoloading: `spl_autoload_register()` o Composer

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →