PHP object-oriented explanation _ PHP Tutorial

Source: Internet
Author: User
PHP object-oriented explanation. Three main properties of an object: actions that can be performed on the object. turning on the light is the action. Object form: the three main features of a color object are applied when the methods are used to respond to objects.
Object Behavior: you can perform operations on the object. if you turn on the light, turning off the light is behavior.
Object form: how the object responds, colors, dimensions, and shapes are applied.
Object representation: the representation of an object is equivalent to an ID card, which specifically distinguishes between the same behavior and status.

Object-oriented model

Object-oriented concepts:
Oop (object-oriented programming) can make its code simpler and easier to maintain and has stronger reusability.

What is a class:
A class is a collection of objects with the same attributes and services, such as people, books, ships, and vehicles. It provides a unified abstract description for objects of this class, in programming languages, a class is a separate program. it should have a class name that includes two parts: attribute description and service.
What is an object:
An object is an entity that describes objective events in the system. it is a basic unit of the system. * Data and code are bundled into one entity. * An object consists of a group of attributes and a group of actions that operate on these attributes.
From an abstract point of view, an object is an abstraction of a problem domain or something in the domain. It reflects the information stored in the system and its role: it is a set of attributes and an encapsulation body that has the right to operate on these attributes. The objective world is composed of links between objects.
Relationships between classes and objects:
The relationship between a class and an object is like the relationship between a mold and a casting. the result of the strength of a class is an object, and the abstraction of an object is a class, class describes a group of objects with the same properties and behaviors.

Classes and attributes and methods

Syntax format for defining classes in PHP:

The code is as follows:


Class classname [optional attributes] {
Public $ property [= value];… // Declare a public ID with public, and assign values to a variable.
Function functionname (args) {// member function in the class method
Code }...
// Class method (member function)
}


Generate an object (class instantiation): $ object name = new classname ();

Use object attributes

In a class, you can access a special pointer $ this. when this class is set or accessed through an operation, $ this-> name is used for reference.
Object generation
Define a class and declare it with a new one. because of the encapsulation characteristics of object data, objects that cannot be directly accessed by the main program block must call the attributes and behavior functions defined in the class through the object to indirectly achieve the purpose of accessing the data in the control class.
Relationship between objects and classes
Relationship between objects and classes:
An object actually exists and occupies dynamic resources.
A class is the blueprint of an object and may occupy static resources.
Object attributes occupy dynamic resources
The class (static) attribute is actually a "global variable" in the class namespace"
Performance considerations:
Each object occupies data space separately.
The added invocation level may consume execution time.
Method parameter form and transmission method
Method parameters can be basic data types, arrays, and class objects.
Basic data type: passing value parameters
Array: passing value parameters
Class object: reference transfer
Constructor
Constructor is used for class initialization.
Like other functions, the constructor must be named _ construct ().
Syntax format:
Function _ construct (parameter ){
........
}
Example:

The code is as follows:


Class Person {
Public $ name;
Public $ sex;
Public $ age;
Function _ construct ($ name, $ sex, $ age ){
Echo "I'm a constructor
";
$ This-> name = $ name;
$ This-> sex = $ sex;
$ This-> age = $ age;
}


Output result: Initialization

Destructor

When an object is out of its scope (for example, the function of the object has been called), the system automatically executes the destructor. Memory should be released in the destructor before exiting.
The Destructor _ destruct does not have any parameters.
Example:

The code is as follows:


Class person {
Function _ destruct ()
{Echo "bye! ";}
}
$ A = new person ();


Access type
Public (public modifier) class can be accessed both inside and outside the class
Private (private modifier) can only be accessed within the class
The protected (protected member modifier) subclass of protected can access the outside of the class.

Three important features of oop

Encapsulation, inheritance, and polymorphism
Encapsulation: encapsulation combines object attributes and behaviors into an independent unit.
Two steps are required to encapsulate a class. The first step is to privatize a class. The second step is to use the set and get operations to read and assign values.
Its advantage is: hiding the implementation details of the class can facilitate logical control, restrict unreasonable operations on the attribute, and facilitate modification and enhance the maintainability of the code.

_ Get and _ set
Generally, class private words are more in line with the actual logic.
Predefined functions are used to obtain and apply values.
_ Get is usually the value of the domain.
_ Set is usually the value of the field.
_ Call when calling a method that does not exist in an object, an error call () is generated to handle this situation.

Static attributes and methods

Static keywords to declare static methods
Static variables generate a static variable within the class, that is, they can be combined by the strength of all classes. that is to say, static members are placed in the "initialize static segments ", when the class is loaded for the first time, every object in the heap memory can be shared.
Usage: self: $ static property, self: static method
Static function p (){
Echo self: $ country;
Echo self: PI; // access constant
// Echo $ this-> name; only static attributes can be operated in static methods.
// Self: p ();
}
External call: Class: $ static property, class: static method

Const keyword: used to generate a constant is the only constant that cannot be changed. the constant is capitalized.
Const CONSTANT = 'constant value'; generate a constant
Echo self: CONSTANT; // class internal access
Echo ClassName: CONSTANT; // class external access

Inheritance

Class B objects have all attributes and behaviors of Class A, which are called B's inheritance of Class.
If a class inherits attributes and services from multiple classes, this is called multi-inheritance, we usually become the inheritance class as the subclass, and the inheritance class as the parent class. in PHP, there is only single inheritance, however, a parent class can be inherited by multiple classes, but a subclass can only have one parent class, but can be inherited by association. the class definition can be reduced through inheritance.
Extende declares an inheritance relationship
Syntax format: class B extends A this example indicates that B inherits
Class external access is valid for subclass
Attributes and methods of child classes and parent classes
The subclass inherits all the content of the parent class, but the private part of the parent class cannot be directly accessed.
The newly added attributes and methods in the subclass are extensions of the parent class.
The attributes defined in the subclass with the same name as the parent class overwrite the parent class attributes, and the methods with the same name overwrite the parent class methods.

Override method

In the subclass, use parent to access the overwritten attributes and methods in the parent class.

Parent: :__ construce ();
Parent: $ name;
Parent: fun ();

Overwrite original attributes of the parent class
Syntax format: $ c = clone $ p; $ c. The Object $ p outputs echo $ c-> name;

Object comparison
=== Two comparison operators.
= Compares the content of two objects.
= Is the compare object handle, that is, the reference address.

The instanceof operator is used to check whether the object strength belongs to the type of a certain class. if true is returned, false is returned.
_ Clone () if you want to change the content of the original object after cloning, you need to rewrite the original attributes and methods in _ clone ().
Function _ clone (){
$ This-> name = "I am a clone ";
}

Final indicates that a class is the final version, which means it cannot be called in the quilt class.

Polymorphism

Polymorphism refers to the inheritance of attributes or behaviors defined in the parent class. it can have different data types or show different behaviors. This makes the same attribute or behavior have different semantics in the parent class and its sub-classes.
That is to say, the execution results of the same method in the subclass and parent classes are different.

The code is as follows:


Class {
Function info (){
Echo "a info ";
}
}
Class B extends {
Function info (){
Echo "B INFO ";
}
}
Class C extends {
Function info (){
Echo "c info ";
}
}
Function printinfo ($ obj ){
Function printinfo (A $ obj ){
If ($ obj instanceof)
$ Obj-> info ();
$ Obj-> info ();
}
}
$ A = new A (); $ B = new B (); $ c = new C ();
Printinfo ($ a); // output A INFO
Printinfo ($ B); // output B INFO
Printinfo ($ c); // Output C INFO



Abstract methods and abstract classes

The abstract method is used as a subclass.

The code is as follows:


Abstract class Person {
Public $ name;
Abstract function getInfo ();
}


Abstract classes cannot be powerful. an abstract class must have an abstract method. However, dynamic functions can be defined in abstract classes.
Interface
After a class inherits an interface, it must overwrite all the methods of the interface. the interface can only declare constants, and the methods of the interface must be defined as common. Otherwise, the class cannot be inherited, interfaces can be inherited from multiple interfaces.
Syntax:

The code is as follows:


Interface PCI {
Const TYPE = "PCI ";
// Public $ name; error
Function start ();
Function stop ();
}


The method in the interface can be declared as static

The code is as follows:


Interface A {function ();}
Interface B {function B ();}
Interface C extends A {function c ();}
Class D implements B, C {
Function (){}
Function B (){}
Function c (){}
}


Class
Class declaration:

The code is as follows:


Permission modifier class name {// permission modifier: public, protected, private, or omitted 3.
// Class body; // class is the key word for creating a class
} // The class name must be followed by the class and followed by the member of the class placed.
?>
// Ps: you can add a permission modifier before the class keyword, static, abstract, and other keywords. A class, that is, all the content between a pair of braces must be in a piece of code, and the content in the class cannot be divided into blocks.
Class ConnDB {
//....
?>
//...
};
?>


Member attributes:
The variables directly declared in the class are called member attributes/Variables. they can be of the scalar type and compound type in php, and the resource type and null type are invalid.
In addition, when declaring a member attribute, you must have a keyword to modify it: public, protected, private; no specific significance is required: var. when declaring a member attribute, there is no need to assign an initial value.

Member constants:

Modified with a const constant, for example, const PI = 3.1415926;
Constant output does not need to be instantiated. it can be directly called by class name + constant name. The format is: class name: constant name
Ps. special access methods: -------- "$ this" and "::"
1) $ "this" exists in each member method, which is a special object to use. the member method belongs to that object, and the $ this application represents that object. its function is to complete access between members of the object.
2) ":" becomes the scope operator. with this operator, you can call constants, variables, and methods in the class without creating objects. the syntax format is as follows:

Keywords: variable name/constant name/method name

Keyword: parent, which can call the member variables, member methods, and constants in the parent class member;
Self, which can call static members and constants in the current class;
Class name, which can call constants, variables, and methods in the class;
  
Member method:

A function declared in a class becomes a member method. multiple functions can be declared in a class, that is, an object can have multiple member methods. the declaration of the member method is the same as that of the function. the only special feature is that the member method can be modified with keywords to control its access permissions.
Class instantiation

  Creation object:

$ Variable name = new class name ([parameter]); // class instantiation.
Member class:
$ Variable name-> member attribute = value;
Constructor and constructor
The constructor is the first method automatically called by the object after the object is created. it exists in the declaration of each class and is a special member method, which is generally used to complete some initialization operations. if no constructor exists in the class, a constructor without parameters is automatically generated by default.
Format:

The code is as follows:


Function _ construct (parameter list ){
// Method body
};


The Destructor is the opposite of the constructor. it is the last method called before the object is destroyed. it completes a specific operation, such as closing the file and releasing the memory.
Format:

The code is as follows:


Function _ destruct (){
// Method body
};


Object-oriented features: encapsulation, abstraction, and polymorphism.
Encapsulation:
Combine the member attributes and methods in the class into an independent unit, and hide the content details of the object as much as possible. the purpose is to prevent external errors from affecting internal data by ensuring that the internal data (member attributes and member methods) of the class cannot be accessed at will.
Class encapsulation is implemented through the public, private, protected, static, and final keywords. for the role of each keyword, see the relevant php documentation.
Inheritance:
Make a class inherit and have the member attributes and member methods of another existing class. the inherited class becomes the parent class, and the inherited class becomes the child class. inheritance can improve code reusability and maintainability. the extends keyword is used for class inheritance.
Format:

The code is as follows:


Class subclass name extends parent class name {
// Subclass method body.
}


The parent: keyword can also be used to call the member method of the parent class in the subclass method. the format is as follows:
Parent: Member method (parameter) of the parent class );

Methods that overwrite the parent class:

The so-called method that overwrites the parent class, that is, the method inherited from the parent class is replaced by the method in the subclass, also called method rewriting. the key to rewriting is to create the same method as the parent class in the subclass. g includes the method name, parameter, and return type.

Polymorphism:
Polymorphism refers to the ability of a program to process multiple types of objects. php polymorphism can be implemented in two ways, namely, polymorphism through inheritance and polymorphism through interfaces.
Realize polymorphism through inheritance, that is, rewrite the inherited member method to achieve polymorphism.

The code is as follows:



Abstract class ParentClass {
Abstract function printMessage ();
}
Class SubClassA extends ParentClass {
Function printMessage (){
Echo "I am message from class ";
}
}
Class SubClassB extends ParentClass {
Function printMessage (){
Echo "I am message from class B ";
}
}
Function printMSG ($ object ){
If ($ object instanceof ParentClass ){
$ Object-> printMessage ();
} Else {
Echo "error! ";
}
}
$ ObjectA = new SubClassA ();
PrintMSG ($ objectA );
$ ObjectB = new SubClassB ();
PrintMSG ($ objectB );
?>


Implement polymorphism through interfaces, define interfaces, and empty methods. then class inherits interfaces.

The code is as follows:



Interface interfaceInfo {
Function printMessage ();
}
Class ClassA implements interfaceInfo {
Function printMessage (){
Echo "message form class ";
}
}
Class ClassB implements interfaceInfo {
Function printMessage (){
Echo "message form class B ";
}
}
Function printMSG ($ object ){
If ($ object instanceof interfaceInfo ){
$ Object-> printMessage ();
} Else {
Echo "error! ";
}
}
$ ObjectA = new ClassA ();
PrintMSG ($ objectA );
$ ObjectB = new ClassB ();
PrintMSG ($ objectB );
?>


Ps. abstract classes and interfaces.
Abstract classes and interfaces are special classes that cannot be instantiated. they can be used together with object-oriented polymorphism.
Abstract class:
An abstract class is a class that cannot be instantiated. it can only be used as the parent class of other classes. abstract classes are declared using abstract keywords. the format is as follows:

The code is as follows:


Abstract class name {
Abstract function Member method (parameter );//
}


Abstract classes are similar to common classes, including member variables and member methods. the difference between the two is that an abstract class must contain at least one abstract method. abstract methods do not have a method body. the implementation of their functions can only be completed in sub-classes. abstract methods are also modified using the keyword abstract.

Interface:
The inheritance feature simplifies the creation of objects and classes and enhances code reusability. However, php only supports single inheritance. if you want to implement multiple inheritance, you must use interfaces.
Interface declaration: implemented by using the interface keyword. the methods declared in the interface must be abstract methods. variables cannot be declared in the interface and can only be declared as member attributes of constants using the const keyword, all the members in the interface must have the puclic access permission. the ainterface declaration interface format is as follows:

The code is as follows:


Inerface interface name {
// Constant member; // the member can only be a constant.
// Abstract method;
}


Because the interface cannot implement the instantiation operation, it can only be implemented in the form of the subclass inheritance interface. the implementation format is:

The code is as follows:


Class subclass name implements interface name 1 [, interface name 2, interface name 3,...] {
// Subclass method body.
}


Common keywords:
1) final: final indicates the final and final. this means that the classes and methods modified by the final keyword are all final versions. it cannot be inherited or be a subclass. it cannot be rewritten or overwritten.
2) static: the member attributes and member methods modified with the static keyword are called static attributes and static methods. static member attributes and methods can be directly used without being instantiated.
Static attribute: it belongs to the class itself, but does not belong to any instance of the class. it is equivalent to a global variable stored in the class and can be accessed through the class anywhere. the access format is:
Class name: $ static property name;
If you want to access static attributes in the Member methods inside the class, add the operator "self:" Before the static attribute name.
Static method: because it is not restricted by any objects, you can directly reference static methods in the class without class instantiation. the reference format is as follows:
Class name: static method name (parameter );
If you want to call static methods in the Member methods inside the class, add the operator "self:" Before the static method name. in a static method, only static variables can be called, but normal variables cannot be called. in a normal method, static variables can be called.
In addition to non-instantiation, static members are used to retain the static data modified after the object is destroyed so that it can be called next time.
3) clone. object cloning can be achieved through keywords. the clone object has no relationship with the original object, that is, the cloned object will apply for a new bucket to store the original object content. the format is as follows:
$ Clone object = clone $ name of the original clone object;
After cloning, their n member methods, attributes, and values are exactly the same. if you want to re-initialize the copy, you need to use _ clone ().
Magic method _ clone () can re-initialize the cloned copy object. it does not need any parameters, and automatically contains $ this (copy object) and $ that (original object) object references.
Object comparison:
"=" Indicates comparing the content of two objects, "=" indicates comparing the reference addresses of two objects is equal.
Object Type detection: the instanceof operator can detect the object that the current object belongs.

Object-oriented --- Common magic methods:
The common magic methods we have learned above include _ construct (), _ destruct (), and _ clone. next we will introduce several common magic methods.
_ Get (), _ set ();
The preceding two methods are used to precisely copy private members or obtain values.
_ Set () sets a value for the private member attribute during the program running. it does not require any return value. the _ set () method includes two non-negligible parameters: variable name and variable value. this method does not need to be called proactively. you can add the prive keyword to the method money.
_ Get (): When the program is running, obtain the attribute value of the private member outside the object. it has a parameter: Private member attribute name. it returns a value that allows the object to be used externally. you are not allowed to call this method.

_ Isset (), _ unset ():
The isset () function is used to check whether a variable exists. in object-oriented systems, the isset () function can be used to detect public member attributes, but this function does not work for private member attributes. therefore, the _ isset () function is created for this purpose. the format is as follows:
Bool _ isset (string name );
_ Unset () is also used to delete the private member attributes of the specified variables and objects. the format is as follows:
Void _ unset (string name );//
_ Call ():
The _ call () method is used by php to call a non-existent or invisible member method () method to store the method name and its parameters (method name and method parameters ). the method parameters exist as arrays.
_ ToString () method:
The function is to convert an object into a string when echo or print is used to output the object.
If the _ toString () method is not available, a fatal error occurs when an object is directly output.
When outputting an object, note that the echo or print statement is followed by the object to be output directly. do not add any extra characters in the middle. otherwise, _ toSting () will not be executed.
_ Autoload () method:
Save an independent and complete class to a php page, and keep the file name consistent with the class name. this is a good habit for every developer. in this way, you can easily find it next time you use it. however, if you want to introduce many classes on a page, you need to use the include_once () function or the require_once () function to introduce them one by one. the _ autoload () method introduced in php5 can automatically instantiate the class to be used. when a class is not instantiated, _ autoload () automatically searches for files with the same class name under the specified path. if it is found, the execution continues; otherwise, an error is returned.

The code is as follows:



Function _ autoload ($ class_name ){
$ Class_path = $ class_name. '. class. php ';
If (file_exists ($ class_path )){
Include_once ($ class_path );
} Else {
Echo 'The class does not exist or the class path is incorrect ';
}
}
$ Class = new Class (); // it will be automatically loaded.
Echo $ class; // output class content. if the _ toString () method is customized, the content defined in _ toString () is output.
?>

Actions of the objects: operations that can be performed on objects. turning on the light is an action. Object form: when the method is applied, how the object responds, the color...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.