PHP Basics: Object-Oriented Programming

1. Class Definition

  • class keyword + class name + {}, variables and methods are defined in curly brackets.
  • Variables of a class are declared using var and can also be initialized by value.
  • After a class is created, you can use the new operator to instantiate objects of that class.
  • Note: The variable $this represents its own object.

2. Member functions

  • Constructor: used to initialize an object when creating an object, that is, assign initial values ​​to object member variables, and use it with the new operator in the object creation statement.
    void construct ([ mixed $args [, $... ]] )
  • Destructor: When the object ends its life cycle (for example, the function where the object is located has been called), the system automatically executes the destructor.
    void destruct ( void )

3. Inheritance

  • PHP uses the keyword extends to inherit a class and does not support multiple inheritance.
    Class A extends B{} //Class A inherits Class B
  • PHP does not automatically call the superclass's constructor in the subclass's constructor. To execute the constructor of the parent class, you need to call parent::construct() in the constructor of the child class.
  • Method overriding: If the method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called method overriding, also known as method overriding.

4. Access Control

  • PHP access control of properties or methods is achieved by adding the keyword public (public), protected (protected) or private (private) in front.
  • Class properties must be defined as one of public, protected, private. If defined with var, it is considered public.
  • Methods in a class can be defined as public, private or protected. If none of these keywords are set, the method defaults to public.

5. Interface

  • Specifies which methods a class must implement without defining the specifics of those methods.
  • An interface is defined by the interface keyword, and the defined methods must be public.
    Interface A{} * //声明一个A接口*
  • To implement an interface, use the implements operator. The class must implement all the methods defined in the interface, otherwise a fatal error will be reported. A class can implement multiple interfaces, using commas to separate the names of multiple interfaces.
    class B implements A,C //实现A,C接口

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325947212&siteId=291194637