- Объектно-ориентированный PHP с классами и объектами
- Что такое объектно-ориентированное программирование (ООП)?
- Что такое класс PHP?
- PHP OOP
- Section 1. Objects & Classes
- Section 2. Constructor and Destructor
- Section 3. Properties
- Section 4. Inheritance
- Section 5. Abstract classes
- Section 6. Interfaces
- Section 7. Polymorphism
- Section 8. Traits
- Section 9. Static methods & properties
- Section 10. Magic Methods
- Section 11. Working with Objects
- Section 12. Namespaces
- Section 13. Autoloading
- Section 14. Exception Handling
- Section 15. Class / Object Functions
Объектно-ориентированный PHP с классами и объектами
Sajal Soni Last updated Dec 4, 2018
В этой статье мы исследуем основы объектно-ориентированного программирования на PHP. Начнем с введения в классы и объекты, а во второй половине статьи обсудим несколько продвинутых понятий, таких как наследование и полиморфизм.
Что такое объектно-ориентированное программирование (ООП)?
Объектно-ориентированное программирование, обычно называемое ООП — это подход, который вам помогает разрабатывать сложные приложения таким образом, чтобы они легко поддерживались и масштабировались в течение длительного времени. В мире ООП реальные понятия Person , Car или Animal рассматриваются как объекты. В объектно-ориентированном программировании вы взаимодействуете с вашим приложением, используя объекты. Это отличается от процедурного программирования, когда вы, в первую очередь, взаимодействуете с функциями и глобальными переменными.
В ООП существует понятие «class», использываемое для моделирования или сопоставления реального понятия с шаблоном данных (свойств) и функциональных возможностей (методов). «Оbject» — это экземпляр класса, и вы можете создать несколько экземпляров одного и того же класса. Например, существует один класс Person , но многие объекты person могут быть экземплярами этого класса — dan , zainab , hector и т. д.
Например, для класса Person могут быть name , age и phoneNumber . Тогда у каждого объекта person для этих свойств будут свои значения.
Вы также можете определить в классе методы, которые позволяют вам манипулировать значениями свойств объекта и выполнять операции над объектами. В качестве примера вы можете определить метод save , сохраняющий информацию об объекте в базе данных.
Что такое класс PHP?
Класс — это шаблон, который представляет реальное понятие и определяет свойства и методы данного понятия. В этом разделе мы обсудим базовую анатомию типичного класса PHP.
Лучший способ понять новые концепции — показать это на примере. Итак, давайте рассмотрим в коде класс Employee , который представляет объект служащего.
PHP OOP
This PHP OOP series helps you master Object-oriented Programming in PHP.
PHP introduced object-oriented programming features since version 5.0. Object-Oriented programming is one of the most popular programming paradigms based on the concept of objects and classes.
PHP OOP allows you to structure a complex application into a simpler and more maintainable structure.
Section 1. Objects & Classes
- Objects & Classes – learn the basic concepts of OOP including objects and classes.
- The $this keyword – help you understand PHP $this keyword and how to use it effectively.
- Access Modifiers: public vs. private – explain to you the access modifiers in PHP and help you understand the differences between the private and public access modifiers.
Section 2. Constructor and Destructor
- Constructor – explain to you the constructor concept and how to use it to initialize attributes.
- Destructor – learn how to use destructor to clean resources when the object is deleted.
Section 3. Properties
- Typed Properties – show you how to add type hints to class properties.
- Readonly Properties – use the readonly keyword to define readonly properties that can be initialized once within the class.
Section 4. Inheritance
- Inheritance – how to extend a class for code reuse.
- Call the parent constructor – show you how to call the parent constructor from a child class’s constructor.
- Overriding method – guide you on how to override a parent class’s method in the child class.
- Protected Access Modifier – explain the protected access modifier and how to use protected properties and methods effectively.
Section 5. Abstract classes
Section 6. Interfaces
Section 7. Polymorphism
- Polymorphism – explain the polymorphism concept and show you how to implement polymorphism in PHP using abstract classes or interfaces.
Section 8. Traits
Section 9. Static methods & properties
- Static Methods and Properties – show you how to use static methods and properties.
- Class constants – learn how to define class constants using the const keyword.
- Late Static Binding – introduce the late static binding concept and how to use it effectively.
Section 10. Magic Methods
- Magic methods – understand how the magic methods work in PHP.
- __toString() – return the string representation of an object.
- __call() – show you how to use the __call() magic method.
- __callStatic() – show you how to use the __calStatic() magic method.
- __invoke() – learn how to define a function object or function by implementing the __invoke() magic method.
Section 11. Working with Objects
- Serialize Objects– use the serialize() function to serialize an object into a binary string and how to use the __serialize() and __sleep() magic methods
- Unserialize Objects – guide you on how to use the unserialize() function to convert a serialized string into an object. Also, discuss the __wakeup() and __unserialize() magic methods.
- Cloning Objects – show you how to copy an object.
- Comparing Objects – how to compare two objects.
- Anonymous class – learn how to define a class without a declared name.
Section 12. Namespaces
Section 13. Autoloading
- Autoloading Class files – learn how to load classes automatically.
- Autoloading using Composer – show you how to use Composer to autoload classes.
Section 14. Exception Handling
- try…catch – show you how to use the try…catch statement to handle exceptions that may occur in your script.
- try…catch…finally – learn how to clean up the resources when an error occurs using the finally block.
- Throw an exception – guide you on how to throw an exception using the throw statement.
- Set an Exception Handler – show you how to use the set_exception_handler function to set a global exception handler to catch the uncaught exceptions.
Section 15. Class / Object Functions
- class_exists – return true if a class exists
- method_exists – return true if an object or a class has a specific method.
- property_exists – return true if an object or a class has a specific property.