Object in oop php

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.
Читайте также:  React typescript web components

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.
Читайте также:  Method to convert string to int in java

Источник

PHP OOP — Classes and Objects

A class is a template for objects, and an object is an instance of class.

OOP Case

Let’s assume we have a class named Fruit. A Fruit can have properties like name, color, weight, etc. We can define variables like $name, $color, and $weight to hold the values of these properties.

When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

Define a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces (<>). All its properties and methods go inside the braces:

Syntax

Below we declare a class named Fruit consisting of two properties ($name and $color) and two methods set_name() and get_name() for setting and getting the $name property:

class Fruit // Properties
public $name;
public $color;

// Methods
function set_name($name) $this->name = $name;
>
function get_name() return $this->name;
>
>
?>

Note: In a class, variables are called properties and functions are called methods!

Define Objects

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.

Objects of a class are created using the new keyword.

In the example below, $apple and $banana are instances of the class Fruit:

Example

class Fruit // Properties
public $name;
public $color;

// Methods
function set_name($name) $this->name = $name;
>
function get_name() return $this->name;
>
>

$apple = new Fruit();
$banana = new Fruit();
$apple->set_name(‘Apple’);
$banana->set_name(‘Banana’);

echo $apple->get_name();
echo «
«;
echo $banana->get_name();
?>

In the example below, we add two more methods to class Fruit, for setting and getting the $color property:

Example

class Fruit // Properties
public $name;
public $color;

// Methods
function set_name($name) $this->name = $name;
>
function get_name() return $this->name;
>
function set_color($color) $this->color = $color;
>
function get_color() return $this->color;
>
>

$apple = new Fruit();
$apple->set_name(‘Apple’);
$apple->set_color(‘Red’);
echo «Name: » . $apple->get_name();
echo «
«;
echo «Color: » . $apple->get_color();
?>

PHP — The $this Keyword

The $this keyword refers to the current object, and is only available inside methods.

Look at the following example:

Читайте также:  Проверка элементов массива на уникальность php

Example

So, where can we change the value of the $name property? There are two ways:

1. Inside the class (by adding a set_name() method and use $this):

Example

class Fruit public $name;
function set_name($name) $this->name = $name;
>
>
$apple = new Fruit();
$apple->set_name(«Apple»);

2. Outside the class (by directly changing the property value):

Example

class Fruit public $name;
>
$apple = new Fruit();
$apple->name = «Apple»;

PHP — instanceof

You can use the instanceof keyword to check if an object belongs to a specific class:

Источник

Объектно-ориентированный PHP с классами и объектами

Sajal Soni

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 , который представляет объект служащего.

Источник

Оцените статью