Home >Backend Development >PHP Tutorial >PHP, Classes and Objects

PHP, Classes and Objects

Barbara Streisand
Barbara StreisandOriginal
2024-12-29 14:42:11881browse

PHP, Classes and Objects

Classes and Objects in PHP

PHP, like Java, supports object-oriented programming and uses classes and objects as its core building blocks. Understanding these concepts is essential for mastering PHP. This guide will cover everything you need to know about classes and objects in PHP.

Defining a Class

A class in PHP is a blueprint for creating objects. It defines the structure and behavior that the objects of the class will have.

Syntax

class ClassName {
    // Properties (Fields)
    // Methods
}

Example

class Car {
    // Properties
    public $color;
    public $model;
    public $year;

    // Methods
    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Creating Objects

Objects are instances of classes. You create an object from a class using the new keyword.

Syntax

$objectName = new ClassName();

Example

class Main {
    public function run() {
        $myCar = new Car(); // Creating an object of the Car class
        $myCar->color = "Red";
        $myCar->model = "Tesla";
        $myCar->year = 2022;
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

Properties and Methods

Properties (also known as fields) represent the state of an object, while methods define the behavior of the object.

Properties

Properties are variables that hold the data of an object.

Example

class Car {
    public $color;
    public $model;
    public $year;
}

Methods

Methods are functions defined within a class that describe the behaviors of the objects.

Example

class Car {
    public $color;
    public $model;
    public $year;

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Constructors

Constructors are special methods that are automatically called when an object is instantiated. They initialize the newly created object.

Default Constructor

If no constructor is defined, PHP provides a default constructor with no arguments.

Example

class Car {
    public $color;
    public $model;
    public $year;

    // Default constructor
    public function __construct() {
    }

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Parameterized Constructor

A parameterized constructor allows you to initialize an object with specific values.

Example

class Car {
    public $color;
    public $model;
    public $year;

    // Parameterized constructor
    public function __construct($color, $model, $year) {
        $this->color = $color;
        $this->model = $model;
        $this->year = $year;
    }

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Using the Parameterized Constructor

class Main {
    public function run() {
        $myCar = new Car("Red", "Tesla", 2022);
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

Constructor Overloading

PHP does not natively support method overloading like Java, but you can simulate it using optional parameters or by handling arguments manually within a single constructor.

Example

class Car {
    public $color;
    public $model;
    public $year;

    // Simulating constructor overloading
    public function __construct($color = "Unknown", $model = "Unknown", $year = 0) {
        $this->color = $color;
        $this->model = $model;
        $this->year = $year;
    }

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Using the Simulated Overloaded Constructor

class Main {
    public function run() {
        $defaultCar = new Car();
        $defaultCar->displayInfo();

        $myCar = new Car("Red", "Tesla", 2022);
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

Encapsulation, Access Modifiers, and Static Members in PHP

Encapsulation

Encapsulation in PHP is the practice of bundling data (properties) and methods (functions) within a class. It ensures the internal state of an object is safe from outside interference and misuse.

Access Modifiers

Access modifiers in PHP control the visibility and accessibility of properties, methods, and constructors. PHP supports three main access modifiers:

  • public: Accessible from anywhere.
  • protected: Accessible within the class, subclasses, and the same package.
  • private: Accessible only within the defining class.

Example Usage:

class ClassName {
    // Properties (Fields)
    // Methods
}

Static Members

Static members in PHP are associated with the class itself rather than any specific instance. They can be accessed without creating an object of the class.

Static Properties:

Static properties are shared among all instances of a class. They are declared using the static keyword.

class Car {
    // Properties
    public $color;
    public $model;
    public $year;

    // Methods
    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Static Methods:

Static methods are declared using the static keyword. They belong to the class rather than an instance.

$objectName = new ClassName();

Accessing Static Members:

Static members are accessed using the class name, not through an object.

class Main {
    public function run() {
        $myCar = new Car(); // Creating an object of the Car class
        $myCar->color = "Red";
        $myCar->model = "Tesla";
        $myCar->year = 2022;
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

Access Modifiers in PHP

Access modifiers in PHP control the visibility of class members, ensuring encapsulation and enforcing access restrictions.

Types of Access Modifiers

  1. public
  2. protected
  3. private

1. public

  • Accessible from: Anywhere.
  • Usage: Use public for members that need to be widely accessible.
class Car {
    public $color;
    public $model;
    public $year;
}

2. protected

  • Accessible from: Within the class and its subclasses.
  • Usage: Use protected for members that should only be accessed within the class hierarchy.
class Car {
    public $color;
    public $model;
    public $year;

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

3. private

  • Accessible from: Only within the class.
  • Usage: Use private for members that should not be accessed outside the defining class.
class Car {
    public $color;
    public $model;
    public $year;

    // Default constructor
    public function __construct() {
    }

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Non-Access Modifiers in PHP

Non-access modifiers in PHP modify the behavior of class members without affecting their visibility.

Types of Non-Access Modifiers

  1. static
  2. final
  3. abstract

1. static

  • Usage: Declares properties and methods that belong to the class rather than an instance.
  • Example:
class ClassName {
    // Properties (Fields)
    // Methods
}

2. final

  • Usage: Prevents further modification of methods or inheritance of classes.
  • Variables: PHP does not support final variables.
  • Methods: Final methods cannot be overridden.
  • Classes: Final classes cannot be extended.
  • Example:
class Car {
    // Properties
    public $color;
    public $model;
    public $year;

    // Methods
    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

3. abstract

  • Usage: Declares classes and methods that are incomplete and must be implemented in subclasses.
  • Abstract Classes: Cannot be instantiated.
  • Abstract Methods: Declared without a body and must be implemented by subclasses.
  • Example:
$objectName = new ClassName();

Inheritance in PHP and Access Modifiers

Inheritance

Inheritance in PHP is a mechanism where one class (subclass) can inherit the properties and methods of another class (superclass). It facilitates code reuse and allows for the creation of a hierarchical relationship between classes.

Syntax for Inheritance

class Main {
    public function run() {
        $myCar = new Car(); // Creating an object of the Car class
        $myCar->color = "Red";
        $myCar->model = "Tesla";
        $myCar->year = 2022;
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

Example

class Car {
    public $color;
    public $model;
    public $year;
}

In this example:

  • Animal is the superclass with a property $name and a method eat().
  • Dog is the subclass that inherits $name and eat() from Animal and adds its own method bark().

Access Modifiers in Inheritance

Access modifiers in PHP determine the visibility of class members in subclasses and other parts of the program. They play a key role in inheritance.

Access Modifiers for Normal Attributes and Methods

  • public: Accessible from anywhere.
  • protected: Accessible within the class, subclasses, and within the same package.
  • private: Accessible only within the class where it is declared.
class Car {
    public $color;
    public $model;
    public $year;

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Access Modifiers for Static Attributes and Methods

Static members in PHP are associated with the class rather than any specific instance. They follow the same access rules as non-static members in inheritance.

class Car {
    public $color;
    public $model;
    public $year;

    // Default constructor
    public function __construct() {
    }

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Are Static Methods Inherited?

Static methods are inherited in PHP but cannot be overridden in the same sense as instance methods. When a subclass defines a static method with the same name, it hides the parent class's static method.

class ClassName {
    // Properties (Fields)
    // Methods
}

Access Modifiers for Abstract Methods

Abstract methods in PHP must be defined in abstract classes. The visibility of an abstract method in the superclass determines its visibility in subclasses. Subclasses must implement abstract methods with the same or less restrictive access modifiers.

class Car {
    // Properties
    public $color;
    public $model;
    public $year;

    // Methods
    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Access Modifiers for Final Attributes and Methods

Final methods in PHP cannot be overridden by subclasses, and final classes cannot be extended.

  • Final Methods: Prevent method overriding.
  • Final Classes: Prevent inheritance.
$objectName = new ClassName();

Syntax for Declaring Top-Level Classes in PHP

In PHP, the declaration of top-level classes (classes not nested inside other classes) follows a specific order of keywords. The declaration can include access modifiers, abstract or final keywords, and the class keyword.

Keywords that can be used:

  1. Access modifier: public
  2. Class type: abstract or final

Order:

class ClassName {
    // Properties (Fields)
    // Methods
}

Syntax:

class Car {
    // Properties
    public $color;
    public $model;
    public $year;

    // Methods
    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Important Notes:

  1. PHP assumes public as the default access modifier if none is specified.
  2. A class cannot be both abstract and final simultaneously.
  3. protected and private access modifiers are not allowed for top-level classes.

Example:

$objectName = new ClassName();

Syntax for Declaring Attributes in Classes in PHP

Keywords that can be used:

  1. Access modifiers: public, protected, private
  2. Static modifier: static
  3. Immutable modifier: readonly (introduced in PHP 8.1)

Order:

class Main {
    public function run() {
        $myCar = new Car(); // Creating an object of the Car class
        $myCar->color = "Red";
        $myCar->model = "Tesla";
        $myCar->year = 2022;
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

Syntax:

class Car {
    public $color;
    public $model;
    public $year;
}

Important Notes:

  1. Attributes default to public if no access modifier is specified.
  2. static attributes belong to the class rather than instances.
  3. readonly attributes can only be initialized once, either during declaration or in the constructor (PHP 8.1 ).

Example:

class Car {
    public $color;
    public $model;
    public $year;

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Syntax for Declaring Methods in Classes in PHP

Keywords that can be used:

  1. Access modifiers: public, protected, private
  2. Static modifier: static
  3. Final modifier: final
  4. Abstract modifier: abstract

Order:

class Car {
    public $color;
    public $model;
    public $year;

    // Default constructor
    public function __construct() {
    }

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Syntax:

class Car {
    public $color;
    public $model;
    public $year;

    // Parameterized constructor
    public function __construct($color, $model, $year) {
        $this->color = $color;
        $this->model = $model;
        $this->year = $year;
    }

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Important Notes:

  1. If no access modifier is specified, the method is public by default.
  2. static methods belong to the class, not instances.
  3. final methods cannot be overridden in subclasses.
  4. abstract methods must be declared in an abstract class and cannot have a body.

Example:

class Main {
    public function run() {
        $myCar = new Car("Red", "Tesla", 2022);
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

Abstract Classes in PHP

Abstract classes in PHP are similar to their counterparts in Java, used to define a blueprint for other classes. They contain both abstract methods (methods without implementation) and concrete methods (methods with implementation). Abstract classes are declared using the abstract keyword and cannot be instantiated directly.


1. Introduction to Abstract Classes

An abstract class serves as a base class for derived classes. It defines common behaviors for its subclasses while allowing the implementation of specific methods in those subclasses.


2. Declaring an Abstract Class

To declare an abstract class in PHP, use the abstract keyword before the class keyword.

Example:

class ClassName {
    // Properties (Fields)
    // Methods
}

3. Abstract Methods

Abstract methods are defined in the abstract class but do not have a body. Subclasses must implement all abstract methods.

Example:

class Car {
    // Properties
    public $color;
    public $model;
    public $year;

    // Methods
    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

4. Concrete Methods

Concrete methods in an abstract class have a body and can be inherited by the subclasses as-is or overridden.

Example:

$objectName = new ClassName();

5. Creating Subclasses

Subclasses of an abstract class must implement all its abstract methods unless the subclass is also declared as abstract.

Example:

class Main {
    public function run() {
        $myCar = new Car(); // Creating an object of the Car class
        $myCar->color = "Red";
        $myCar->model = "Tesla";
        $myCar->year = 2022;
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

6. Instantiating Abstract Classes

Abstract classes cannot be instantiated directly. You must use a concrete subclass to create an instance.

Example:

class Car {
    public $color;
    public $model;
    public $year;
}

7. Constructors in Abstract Classes

Abstract classes can have constructors, and their constructors are called when a subclass is instantiated.

Example:

class Car {
    public $color;
    public $model;
    public $year;

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

8. Abstract Classes with Fields and Methods

Abstract classes can include instance variables and concrete methods, providing reusable functionality for subclasses.

Example:

class Car {
    public $color;
    public $model;
    public $year;

    // Default constructor
    public function __construct() {
    }

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

9. Static Methods in Abstract Classes

Abstract classes can contain static methods. Static methods belong to the class and can be called without instantiating it.

Example:

class ClassName {
    // Properties (Fields)
    // Methods
}

Syntax for Declaring Abstract Classes in PHP

Keywords that can be used:

  1. abstract
  2. public, protected, private (access modifiers)

Order:

class Car {
    // Properties
    public $color;
    public $model;
    public $year;

    // Methods
    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Examples:

Abstract Class with Abstract and Concrete Methods

$objectName = new ClassName();

Abstract Class with Fields and Final Methods

class Main {
    public function run() {
        $myCar = new Car(); // Creating an object of the Car class
        $myCar->color = "Red";
        $myCar->model = "Tesla";
        $myCar->year = 2022;
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

Important Notes:

  1. Abstract classes cannot be instantiated directly.
  2. Abstract methods must be implemented by non-abstract subclasses.
  3. Subclasses that do not implement all abstract methods must also be declared abstract.
  4. Concrete methods in abstract classes are optional for subclasses to override.
  5. Abstract classes can have constructors, properties, and constants.
  6. Abstract classes can use any visibility modifiers for their methods and properties.

Interfaces in PHP

An interface in PHP defines a contract for classes that implement it. It specifies the methods a class must implement, but does not provide any method implementations itself. Interfaces allow for more flexible and modular code, enabling classes to adhere to a common set of method signatures, regardless of their inheritance hierarchy.


1. Introduction to Interfaces

An interface in PHP is similar to an abstract class, but it can only define method signatures without any implementation. A class that implements an interface must provide the implementations for all methods declared in the interface. A class can implement multiple interfaces, making interfaces a key part of PHP's support for multiple inheritance of behavior.


2. Declaring an Interface

To declare an interface, use the interface keyword. Interfaces can only contain method declarations (no method bodies), constants, and abstract methods.

Example:

class Car {
    public $color;
    public $model;
    public $year;
}

3. Implementing an Interface

A class that implements an interface must provide implementations for all the methods declared in the interface. A class can implement multiple interfaces, separating them with commas.

Example:

class Car {
    public $color;
    public $model;
    public $year;

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

4. Interface Method Signatures

Methods in interfaces cannot have a body, and they must be public. When a class implements an interface, it must implement these methods exactly as declared in the interface, including the method signature.

Example:

class Car {
    public $color;
    public $model;
    public $year;

    // Default constructor
    public function __construct() {
    }

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

5. Multiple Interface Implementation

A class in PHP can implement multiple interfaces. This allows for more flexibility in designing systems where classes can adhere to different contracts.

Example:

class ClassName {
    // Properties (Fields)
    // Methods
}

6. Interface Constants

Interfaces can contain constants. These constants are automatically public and can be accessed by any class that implements the interface.

Example:

class Car {
    // Properties
    public $color;
    public $model;
    public $year;

    // Methods
    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

7. Interface Inheritance

An interface can extend another interface. This means that the child interface inherits all methods (signatures) from the parent interface, and can also add new methods. A class implementing the child interface must implement all methods from both the parent and child interfaces.

Example:

$objectName = new ClassName();

8. Static Methods in Interfaces

Interfaces cannot contain static methods. All methods declared in an interface must be instance methods. Static methods are not allowed in interfaces, as interfaces define instance-level contracts for the implementing classes.


Syntax for Declaring and Implementing Interfaces in PHP

Keywords that can be used:

  1. interface
  2. public

Order:

class Main {
    public function run() {
        $myCar = new Car(); // Creating an object of the Car class
        $myCar->color = "Red";
        $myCar->model = "Tesla";
        $myCar->year = 2022;
        $myCar->displayInfo();
    }
}

$main = new Main();
$main->run();

Examples:

Interface with Method Signatures

class Car {
    public $color;
    public $model;
    public $year;
}

Interface with Multiple Implementations

class Car {
    public $color;
    public $model;
    public $year;

    public function displayInfo() {
        echo "Model: " . $this->model . "\n";
        echo "Color: " . $this->color . "\n";
        echo "Year: " . $this->year . "\n";
    }
}

Important Notes:

  1. Interface Methods: Methods in an interface must be public and cannot have a body.
  2. Implementing Multiple Interfaces: A class can implement multiple interfaces, separating them with commas.
  3. Access Modifiers: All methods in an interface are implicitly public. Access modifiers like private or protected are not allowed.
  4. Interface Constants: Interfaces can declare constants that are automatically public and can be accessed by implementing classes.
  5. Interface Inheritance: An interface can extend one or more interfaces, combining their method signatures.
  6. Static Methods: Interfaces cannot contain static methods.
  7. Implementing All Methods: A class must implement all methods defined by the interfaces it implements.

The above is the detailed content of PHP, Classes and Objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn