Want to create interactive content? It’s easy in Genially!
OOP in PHP
Daniel Pueyo Soler
Created on January 11, 2024
En esta presentación muestro los 4 principales tipos de estructuras de datos, el desarrollo de una aplicación práctica (y sus requisitos) y otra propuesta de actividad
Start designing with a free template
Discover more than 1500 professional designs like these:
Transcript
OOP - Object Oriented Programming (PHP)
PRESENTATION
Done by Daniel Pueyo. Dec 2024
Siguiente
ÍNDEX
OBJECT ORIENTED PROGRAMMING (PHP)
Relation between clases: Composition & agregation
Classes
Polimorfism
Abstra ct classes & methods
Objects
Interfaces
Encapsulation: Setters y Getters
Inheritance
Next
Back
OBJECT ORIENTED PROGRAMING (POO) WITH PHP
KEY CONCEPTS OF PHP OOP
Next pages explain OOP from the PHP point of view.
Back
Next
OBJECT ORIENTED PROGRAMMING (OOP)
OOP is based on 4 fundamental principles:
What is it?
Object-oriented programming (OOP) is a programming paradigm that organizes software around objects and their interactions, rather than algorithms and processing logic. In OOP, objects represent real-world entities and encapsulate data and related functionality within themselves.
Inheritance
Esto es un párrafo listo para contener creatividad, experiencias e historias geniales.
Polymorphism
Encapsulation
Abstraction
To Learn more
Next
Back
CLASSES
Class elements:
EXERCISE
characteristics:
- A class is a custom data structure or template that contains data and code. Represents any element of real or imaginary life. - The first letter of the classes is capitalized - They consist of a constructor block where the class is initialized with its properties, and another with the class methods
UML:
How do we create a Class?
class My_class(){}
EXAMPLE
SOLUTION
Next
Back
Para saber más
OBJECTS
To create or instantiate an object, we invoke its class with the properties that the constructor of its class expects.
EXERCISE
my_object=My_class(propertie1,propertie2...);
We can access the various properties or methods of the object by using a "->" notation immediately following the object itself. This same principle applies when we want to invoke or call a specific method that belongs to the object.
EXAMPLE
variable=my_object->propertie1; my_object->method1();
SOLUTION
Next
Back
To learn more
ENCAPSULATION
EJERCICIOS
Characteristics
¿Cómo lo hacemos?
Complexity hide
Data protect
Private Methods and properties
Modularity and code reuse
EXAMPLE
Setters
Getters
SOLUCION
Back
Next
To learn more
INHERITANCE
CHARACTERISTICS
EXERCISES
A "child" class inherits methods and attributes from its "parent" class
Inheritance is symbolized by a triangle in a UML diagram
In PHP, inheritance is implemented using the keyword "extends" to indicate the parent class. Example: class Child extends Parent;
UML EXAMPLE
Overriding is the process where a child class provides its own implementation of a method that is already defined in its parent class, replacing the parent's version.
SOLUCION
HOW DO WE DO IT?
Next
Back
To learn more
POLIMORFISMO
CARACTERISTICAS
EJERCICIO
varias clases comparten el mismo nombre de método o atributo
cada clase puede implementar los metodos y atrbutos con el mismo nombre, de manera diferente
De esta forma, un objeto puede comportarse de múltiples formas según el contexto en el que se utiliza
¿Mejor con un ejemplo?
Ejemplo
SOBREESCRITURA
SOLUCION
Siguiente
Volver
Para saber más
RELATIONS BETWEEN CLASSES
EXERCISE
UML symbol:
Types of relations:
Tipos de Relación entre clases
Usage example
AGREGATION
Usage example
COMPOSITION
UML EXAMPLE
SOLUTION
Back
To Learn More
example of encapsulation adventages
Suppose you are creating a class called BankAccount to represent bank accounts in a banking management system. This class has attributes such as accountHolder, balance, and accountNumber. Now, consider the following aspects: Hiding Complexity: Internally, the BankAccount class might have logic to handle transactions, fees, and even to calculate interest. However, from the perspective of the user interacting with a BankAccount object, they only need to know methods such as deposit(), withdraw(), and checkBalance(). The internal complexity of how these operations are managed is hidden from the user, making it easier to use and understand. Data Protection: Sensitive data, such as the balance and account number, is encapsulated within the BankAccount class. This means it can only be accessed and modified through controlled methods, such as deposit() and withdraw(). This prevents unauthorized modifications and ensures the integrity of the data. Modularity and Code Reusability: Suppose you need to create a user interface to display the information of a bank account. Instead of directly accessing the attributes of the BankAccount class, you can use the methods provided by the class to retrieve the necessary information. This promotes modularity, as the logic for accessing and manipulating the data is encapsulated within the BankAccount class.
Composition is a stronger relationship between two classes where one class (called the container class) contains instances of another class (called the contained class) as an integral part of its structure. The contained class cannot exist independently of the container class; its lifecycle is completely controlled by the container class. Characteristics: The container class contains instances of the contained class. The contained class cannot exist without the container class. The relationship between the container class and the contained class is exclusive; an instance of the container class only contains instances of a specific contained class. Usage: It is used when a class needs to have instances of another class as an integral part of its structure and control its lifecycle. Differences with Aggregation: In composition, instances of the contained class cannot exist independently of the container class, whereas in aggregation they can.
<?php class Book { public $title; // The title of the book public $author; // The author of the book public $anio_publicacion; // The year of publication public function __construct($title, $author, $anio_publicacion) { // Constructor to initialize $this->title = $title; $this->author = $author; $this->anio_publicacion = $anio_publicacion; } public function display_info() { // Method to display book information echo "Title: {$this->title} Author: {$this->author} echo "Year of Publication: {$this->anio_publicacion}\n"; } } $book1 = new Book("1984", "George Orwell", 1949); // Create first book $book2 = new Book("To Kill a Mockingbird", "Harper Lee", 1960); // Create second book echo "Book 1:\n"; $book1->display_info(); // Display information of the first book echo "Book 2:\n"; $book2->display_info(); echo "\n"; // Display information of the second book $book1->anio_publicacion = 1950; // Update the publication year of the first book echo "Updated Book 1:\n"; $book1->display_info(); // Display updated information of the first book ?>
En este ejemplo, la clase Perro sobrescribe el método hacer_sonido() heredado de la clase Animal, proporcionando una implementación específica para los perros. Cuando llamamos al método hacer_sonido() en un objeto de tipo Perro, se ejecuta la implementación de la clase Perro, y no la de la clase Animal. Esto es la sobreescritura de métodos en acción.
Escribe una clase llamada Persona que represente a una persona. Esta clase debe tener los siguientes atributos: nombre: el nombre de la persona. edad: la edad de la persona. Implementa setters y getters para los atributos nombre y edad utilizando decoradores.
Crear una clase llamada Empleado que represente a un empleado en una empresa. La clase debe tener los siguientes atributos privados: - nombre: El nombre del empleado (cadena de caracteres). - salario: El salario del empleado (número decimal). La clase debe tener métodos públicos para: - Obtener el nombre del empleado. - Obtener el salario del empleado. - Actualizar el salario del empleado.
EJERCICIOS CLASES
Exercise 1: Creating a "Rectangle" Class Write a class called Rectangle that represents a rectangle in a Cartesian plane. The class must have the following properties and methods: - Properties: Base: The length of the base of the rectangle (decimal number). height: The height of the rectangle (decimal number). - Methods: calculate_area: Method that calculates and returns the area of the rectangle. calculate_perimeter: Method that calculates and returns the perimeter of the rectangle.
<?php //exercise 1class Animal { public function make_sound() { // Method in the base Animal class echo "The animal makes a generic sound.\n";} } class Dog extends Animal { public function make_sound() { // Overriding the method in the Dog class echo "The dog barks: Woof, woof!\n"; } }
<?php //exercise 2class Vehicle { public function accelerate() { // Method in the base Vehicle class echo "The vehicle is accelerating.\n"; } } class Car extends Vehicle { public function accelerate() { // Overriding the method in the Car class echo "The car is accelerating.\n"; } }
Para usar decoradores en Python, sigue estos pasos concisos: - Define una función que actuará como decorador. Esta función tomará otra función como argumento y devolverá una nueva función que modifica el comportamiento de la original. Has de crear uns subfunción que realiza las modificaciones de la función original recibida por parámetro, - Usa la sintaxis @nombre_del_decorador justo encima de la definición de la función que deseas decorar. - Llama a la función decorada como lo harías normalmente. Al llamar a esta función, el decorador se ejecutará automáticamente, modificando su comportamiento según lo definido en la función del decorador.
Exercise 1: Creating an Animal Hierarchy Create a base class called Animal and a subclass called Dog, which inherits from the Animal class. Each class must have a make_sound() method that prints the characteristic sound of the animal.
Exercise 2: Create a base class called Vehicle and a subclass called Car, which inherits from the Vehicle class. Each class must have an accelerate() method that prints a message indicating that the vehicle is accelerating.
En este ejemplo: @property se utiliza para definir un método getter para el atributo x. @x.setter se utiliza para definir un método setter para el atributo x. Dentro de los métodos getter y setter, simplemente estamos accediendo o modificando el atributo _x, que es un atributo protegido. Esto ayuda a encapsular el acceso a los datos de la clase.
Una clase abstracta es una clase que no se puede instanciar directamente y que a menudo contiene al menos un método abstracto, es decir, un método sin implementación.Se utiliza como una plantilla para otras clases que heredan de ella, las cuales deben implementar los métodos abstractos definidos en la clase abstracta. Una interfaz, por otro lado, es una colección de métodos abstractos que una clase puede implementar. A diferencia de una clase abstracta, una interfaz no puede contener implementaciones de métodos; solo define la firma de los métodos que deben implementarse en las clases que la implementan. Ambos conceptos se utilizan para definir una estructura común y proporcionar un contrato para las clases que las implementan, lo que ayuda a garantizar que ciertos métodos estén disponibles y definidos en las clases derivadas.
Ejercicio de Herencia Múltiple Crea una clase llamada Mamifero con un método dar_a_luz que devuelve la frase "Estoy dando a luz a una cría." Crea otra clase llamada Volador con un método volar que devuelve la frase "Estoy volando." Finalmente, crea una clase llamada Murcielago que herede de ambas clases Mamifero y Volador. Esta clase debe tener un método adicional llamado emitir_sonido, que devuelve la frase "¡Soy un murciélago y emito ultrasonidos!" Crea una instancia de la clase Murcielago y muestra ejemplos de uso de sus métodos.
Crear una clase Estudiante que tenga una relación con la clase Universidad y otra con la clase Curso. La clase Estudiante debe tener un atributo universidad que sea una instancia de la clase Universidad, y un atributo cursos que sea una lista de instancias de la clase Curso. Implementa métodos para agregar un curso al estudiante y para mostrar la información del estudiante, incluyendo su universidad y la lista de cursos en los que está inscrito.
<?php class CuentaBancaria { public $titular; // Propiedad pública para el nombre del titular private $saldo; // Propiedad privada para el saldo public function __construct($titular, $saldo_inicial) { // Constructor $this->titular = $titular; $this->saldo = $saldo_inicial; } public function depositar($cantidad) { // Método para depositar dinero $this->saldo += $cantidad; echo "Se han depositado {$cantidad} en la cuenta. Saldo actual: {$this->saldo}\n"; } public function retirar($cantidad) { // Método para retirar dinero if ($cantidad <= $this->saldo) { $this->saldo -= $cantidad; echo "Se han retirado {$cantidad} de la cuenta. Saldo actual: {$this->saldo}\n"; } else { echo "No hay suficiente saldo en la cuenta.\n"; } } public function consultarSaldo() { // Método para consultar el saldo echo "Saldo actual de la cuenta de {$this->titular}: {$this->saldo}\n"; } } $cuentaJuan = new CuentaBancaria("Juan", 1000); // Crear objeto CuentaBancaria $cuentaJuan->depositar(500); // Depositar dinero $cuentaJuan->retirar(200); // Retirar dinero $cuentaJuan->consultarSaldo(); // Consultar saldo ?>
EJERCICIO CON OBJETOS
Write a class called Book that represents a book with the following attributes: - title: The title of the book (string). - author: The author of the book (character string). - anio_publicacion: The year of publication of the book (integer). The class must have a method called display_info() that prints the book information in readable format. Write a test program that creates at least two instances of the Book class, displays the information for each book using the show_info() method, and performs some additional operation, such as changing the publication year of one of the books.
Se te pide que implementes un programa en Python para modelar una calculadora que pueda realizar operaciones matemáticas básicas. Debes crear una clase base llamada OperacionMatematica con un método llamado realizar_operacion() que devuelva un mensaje genérico. Luego, crea al menos dos clases derivadas: Suma y Resta. Cada una de estas clases debe implementar su propia lógica para realizar la operación correspondiente. Finalmente, crea una lista que contenga instancias de ambas clases y recorre la lista, llamando al método realizar_operacion() de cada objeto.
Define una clase abstracta Animal que contenga un método abstracto hacer_sonido(). Luego, crea al menos dos clases concretas que hereden de Animal y que implementen el método hacer_sonido() para representar diferentes tipos de animales, como perros, gatos, pájaros, etc.
1º Importamos ABC, abstractmethod de ABC
2º Definimos la clase abstracta heredada de la clase ABC
3º creamos los métodos abstractos con el decorador @abstractmethod
4º creamos la clase heredada e implementamos sus métodos abstractos
SOLUCIONES
<?php // Rectangle class class Rectangle { // Properties public $base; public $height; // Method to calculate the area of the rectangle public function calculate_area() { return $this->base * $this->height; } // Method to calculate the perimeter of the rectangle public function calculate_perimeter() { return 2 * ($this->base + $this->height); }}
Aggregation is a relationship between two classes where one class (called the container class) contains references to other classes (called contained classes). The container class is not responsible for creating or destroying instances of the contained classes, and the latter can exist independently outside of the container class. Characteristics: The container class has a reference to the contained class. The contained class can exist independently of the container class. The relationship between the container class and the contained class is not exclusive; multiple container classes can reference the same contained class. Usage: It is used when a class needs to use functionalities of another class without being responsible for its lifecycle. Differences with Composition: In aggregation, instances of the contained class can exist outside of the container class, whereas in composition, instances of the contained class are created and destroyed along with the instance of the container class.
Los decoradores en Python son funciones que se utilizan para modificar o extender el comportamiento de otras funciones o métodos. Esto se logra tomando una función como entrada, realizando alguna operación sobre ella y devolviendo una nueva función que puede tener un comportamiento modificado. Los decoradores se aplican utilizando la sintaxis de "@" seguida del nombre del decorador encima de la definición de la función que se desea decorar. Esto hace que la función decorada pase como argumento a la función del decorador, la cual puede realizar alguna acción antes o después de llamar a la función original, modificar sus argumentos o su valor de retorno, o incluso reemplazar completamente la función original por otra. Los decoradores son especialmente útiles para aplicar funcionalidades comunes o repetitivas, como la autenticación, el registro de funciones, la medición del tiempo de ejecución, la gestión de excepciones, entre otros. Al utilizar decoradores, se puede separar la lógica de la funcionalidad principal de una función, lo que mejora la legibilidad, la reutilización y el mantenimiento del código.