Before explaining these three features, let's start with the access modifier.
There are 3 access modifiers in PHP: public protected private;
Public: It is publicly available and can be accessed in this class, subclass, object instance.
Protected: Indicates protected, accessible in this class, subclass, and cannot be accessed in an object instance.
Private: It is privately owned; accessible in this class; not accessible in subclasses, object instances.
First, the encapsulation of
Encapsulation is the extraction of data and the operation of the data is encapsulated together, the data is protected internally, the other parts of the program only authorized operations (methods) to manipulate the data.
classstudent{ Public$name; protected$age; Private$play; Publicfunction __construct ($name, $age) {echo'I'm the Student class .'; $ This->name =$name; $ This->age =$age; }} $student=NewStudent ('Moon', -);
Second, the inheritance of
Code redundancy When multiple classes have many common properties and methods, we can extract the common parts into a class, and subclasses can use this common parent class through some operations, which is called inheritance.
Syntax structure:
Class parent class Name {}
Class subclass name extends parent class name {}
Inheritance Features:
- A subclass can inherit only one parent class (this is direct inheritance), and if you want to inherit the properties and methods of multiple classes, use multiple layers of inheritance
- When a subclass instance is created, the constructor of its parent class is not automatically called by default, and can be done using the parent class:: __construct () or parent::__construct ().
- If the subclass and the parent class have the same method name (public,protected), we are called method overrides or method overrides (override) to see the polymorphism below
classstudent{ Public$name; protected$age; Private$play; Publicfunction __construct ($name, $age) {echo'I'm the Student class .'; $ This->name =$name; $ This->age =$age; }}//Pupil class inherits student classclasspupil extends Student { Publicfunction Testing () {echo'I'm pupil .'; } Publicfunction __construct ($name, $age) {parent::__construct ($name, $age); //calling the parent class's constructor Method 1//student::__construct ($name, $age); //calling the parent class's constructor Method 2echo $ This-name; echo $ This-Age ; //Echo $this->play; //error, parent private defined attribute cannot inherit from quilt class }}NewPupil ('Sky', -);//implementing multilayer inheritance for a classclassa{ Public$name ='AAA';}classB extends a{ Public$age = -;}classC extends b{} $p=NewC (); Echo $p->name;// This will output AAA
PHP Object-oriented three main features: encapsulation, inheritance, polymorphism