Php object-oriented content

Source: Internet
Author: User
Tags autoload php error

Php object-oriented content

1. What is object-oriented?

Object-Oriented Programming (Object Oriented Programming, OOP, Object-Oriented Programming) is a computer Programming architecture, one basic principle of OOP is that a computer program is composed of a single unit or object that can act as a subroutine. OOP achieves three objectives of Software Engineering: reusability, flexibility, and scalability. To achieve the overall operation, each object can receive, process, and send information to other objects.

2. What is a class, what is an object, and the relationship between a class and an object?

Class concept: A class is a set of objects with the same attributes and services. It provides a unified abstract description for all objects belonging to this class, which includes two main parts: attribute and service. In an object-oriented programming language, a class is an independent program unit. It should have a class name and contain two main parts: attribute description and service description.

Object: an object is an entity used to describe objective things in a system. It is a basic unit of a system. An object consists of a group of attributes and a group of services that operate on these attributes. From a more abstract point of view, an object is an abstraction of some things in the problem domain or implementation domain. It reflects the information that the things need to be stored in the system and its role; it is the encapsulation body of a set of attributes and a group of services that have the right to operate on these attributes. The objective world is composed of links between objects.

The relationship between a class and an object is like the relationship between a mold and a casting. The instantiation result of a class is an object, and the abstraction of A Class Object is a class. class describes a group of objects with the same features (attributes) and the same behavior (methods.

3. What is object-oriented programming?

Developing a system program is similar to building a computer classroom. You abstract each independent function module into a class to form an object, which consists of multiple objects, these objects can receive information, process data, and send information to other objects. It constitutes an object-oriented program.

4. How to abstract a class?

Class Definition:

Class name {

}

Use a keyword class and a class name you want and a pair of braces. The structure of this class is defined, and you only need to write code in it.

For example, if a person is an object, how do you recommend a person you are optimistic about to your leadership? Of course, the more detailed the better:

First, you will introduce the person's name, gender, age, height, weight, phone number, home address, and so on.

Then, you will introduce what this person can do. He can drive, speak English, and use a computer.

As long as you have a little introduction, others will have a little understanding of this person. This is our description of a person. Now, Let's sum up that all objects are similar to class descriptions, from the description above, we can see that a class is defined in two parts: static description and dynamic description, static descriptions are what we call attributes, such as the name, gender, age, height, weight, phone number, home address, and so on. It is also the function of the person's object on the fly. For example, when a person can drive, speak English, or use a computer, we can write dynamic functions or methods into a program, functions and methods are the same. Therefore, all classes are written in terms of attributes and Methods. attributes are also called member attributes of this class, and methods are called member methods of this class.

Class {

Member attributes: name, gender, age, height, weight, phone number, home address

Member method: can drive, can speak English, can use a computer

}

Attribute:

Variables are declared by using modifiers in the class definition, that is, the attributes of the class are created. Although the initial values can be specified when the member attributes are declared, however, it is unnecessary to give the initial value of the member attribute when declaring the class.

After the instance outputs an object, we can give the initial value to the member attribute.

For example: $ somevar;

Method (member function ):

The class method is created by declaring a function in the class definition.

For example, function somefun (parameter list)

{......}

5. How to instantiate an object?

The unit of the object-oriented program is the object, but the object is instantiated through the class. Since our class will be declared, the next step is to instantiate the object.

After the class is defined, we use the new keyword to generate an object.

$ Object name = new Class Name ();

Like in PHP, it is also a data type that stores different types of data, and must be loaded to the memory during running, how is the object reflected in the memory? The memory is logically divided into four segments: stack space segments, heap space segments, code segments, and initial static segments. Different declarations in the program are placed in different memory segments, stack space segments are data types that occupy the same length of storage space and small space, such as integer 1, 10,100,100 0, 10000,100 000, and so on, all are 64-bit and 4-byte [A2]. So the data length is not long, and the data type that occupies a large space is put in that memory segment? Such data is stored in the heap memory. Stack memory can be directly accessed, while stack memory cannot be directly accessed. For our objects, it is a type of big data type that occupies an indefinite amount of space. Therefore, objects are placed in the heap, but object names are placed in the stack, in this way, the object can be used through the object name.

6. How to Use members in an object

The PHP Object has two types of members: Member attributes and member methods.

To access members of an object, you must use a special operator "->" to access the object members:

Object-> attribute $ p1-> name; $ p2-> age; $ p3-> sex;

Object-> method $ p1-> say (); $ p2-> run ();

7. Special Reference to the use of "$ this"

Now we know how to access the members in an object. They are accessed through "Object-> member". This is the form of accessing the members in an object outside the object, so what if I want to allow methods in the object to access the attributes of the object, or call other methods of the object through methods in the object? Because all the members in the object must be called by objects, including calls between internal members of the object, a reference to this object is provided in PHP. $ this, each object has an object reference $ this to represent this object and complete the call of the object's internal members.

$ This refers to the reference of this object internally. It is used in the same way as the members of the object called internally and the members of the object called externally.

$ This-> attribute $ this-> name; $ this-> age; $ this-> sex;

$ This-> method $ this-> say (); $ this-> run ();

8. constructor and constructor

Constructor:

Most classes have a special method called constructor. When an object is created, it automatically calls the constructor, that is, when the new keyword is used to instantiate the object, the constructor is automatically called.

The constructor declaration is the same as that of other operations, but its name must be _ construct (). This is a change in PHP5. In previous versions, the name of the constructor must be the same as the class name, which can still be used in PHP5, but it is rarely used now, in this way, the constructor can be made independent of the class name. When the class name changes, you do not need to change the corresponding constructor name. For backward compatibility, if a class does not have a method named _ construct (), PHP will search for a method written in php4 with the same name as the class name.

Format: function _ construct ([parameter]) {...}

Only one constructor can be declared in a class, and a constructor is called only once each time an object is created. This method cannot be called proactively, so it is usually used to execute some useful initialization tasks.

Destructor:

The constructor is opposite to the constructor. The Destructor is newly added to PHP5 and does not contain the destructor in PHP4. The Destructor allows you to perform operations or complete some functions before destroying a class, such as closing a file and releasing a result set, the Destructor is executed when all references to an object are deleted or when the object is explicitly destroyed, that is, the Destructor is called before the object is destroyed in the memory. Similar to the constructor name, The Destructor name of a class must be _ destruct (). The Destructor cannot contain any parameters.

Format: function _ destruct (){......}

9. Encapsulation

Encapsulation is one of the three main features of surface image object programming. encapsulation is to combine object attributes and services into an independent unit and conceal the internal details of objects as much as possible, contains two meanings: 1. combine all attributes of an object with all services to form an inseparable independent unit (that is, an object ). 2. Information Hiding, that is, hiding the internal details of objects as much as possible to form a boundary (or a barrier) for external entities, and retaining only limited external interfaces to associate them with external entities.

The encapsulation principle is reflected in the software: the internal data (attributes) of the object cannot be freely accessed for parts other than the object ), this effectively avoids the "cross-infection" caused by external errors, so that software errors can be localized, greatly reducing the difficulty of error detection and troubleshooting.

Use the private keyword to encapsulate attributes and methods:

Original members:

Var $ name; // The name Of The declarer

Var $ sex; // declare the gender of a person

Var $ age; // declare the person's age

Function run (){.......}

Changed to encapsulation:

Private $ name; // encapsulate a person's name using the private keyword

Private $ sex; // encapsulate the gender of a person using the private keyword.

Private $ age; // encapsulate the age of a person using the private keyword.

Private function run (){......} // Encapsulate the human walking method with the private keyword

Note: As long as there are other keywords before the member attribute, the original keyword "var" should be removed ".

You can encapsulate a member (member attribute and member method) in private mode. The encapsulated members cannot be directly accessed outside the class, and can only be accessed inside the object.

Private Members cannot be accessed externally, because private members can only access the object themselves. For example, the $ p1 object wants to describe its private attributes, you can access the private attribute in the method "say. (No access control is added. The default value is public and can be accessed anywhere)

Private Members can only be used inside the class and cannot be directly accessed outside the class. However, they have access permissions within the class, so sometimes we need to assign values to and read private attributes outside the class, that is, to provide some accessible interfaces to the class, the constructor in the above example is a value assignment form, however, the constructor only assigns a value when creating an object. If we want to assign a value to an existing object, if you also use the constructor to pass values, a new object is created, which is not an existing object. Therefore, we need to make some interfaces that can be accessed externally for private attributes. The purpose is to change and access the attribute values when an object exists, this can be done only for attributes that need to be changed by the outside. The attributes that do not want to be accessed by the outside do not use such interfaces, so as to achieve the purpose of encapsulation, all functions are completed by the object itself, providing as few operations as possible for the outside.

If an interface is provided for the class, you can provide the setting and obtaining methods for private attributes outside the class to operate on private attributes. For example:

Prvate $ age; // Private Property age

Function setAge ($ age) // provides a public age setting method for external users

{

If ($ age130) // when assigning values to an attribute, to avoid setting invalid values to the attribute

Return;

$ This-> age = $ age;

}

Function getAge () // provides a public method for obtaining the age.

{

Return ($ this-> age );

}

10. _ set () _ get () _ isset () _ unset () application of four methods

In general, the class attribute is always defined as private, which is more in line with the actual logic. However, attributes are read and assigned frequently. Therefore, in PHP5, we predefine two functions, "_ get ()" and "_ set () "To obtain and assign values to its attributes, and check the" _ isset () "and the method" _ unset () "of the attributes ()".

In the previous section, we set and obtain each attribute. In PHP5, we provided a method specifically for setting and obtaining values for the attribute, "_ set () "and" _ get () "methods. These two methods do not exist by default, but are manually added to the class, like the constructor (_ construct (), the class will only exist after it is added. You can add these two methods in the following way. Of course, you can also add them in your own style:

// _ Get () is used to obtain private attributes.

Function _ get ($ property_name)

{

If (isset ($ this-> $ property_name )){

Return ($ this-> $ property_name );

} Else {

Return (NULL );

}

}

// _ Set () is used to set Private attributes.

Function _ set ($ property_name, $ value)

{

$ This-> $ property_name = $ value;

}

_ Get (): This method is used to obtain the attribute value of a private member. There is a parameter that is used to input the name of the member attribute you want to obtain and return the obtained attribute value, this method does not need to be manually called and is automatically called when private attributes are directly obtained. Because private attributes have been encapsulated, you cannot directly obtain the value (for example, "echo $ p1-> name ), however, if you add this method to the class, when you use a statement such as "echo $ p1-> name" to directly obtain the value, it will automatically call _ get ($ property_name) to pass the attribute name to the parameter $ property_name. The value of the private attribute we passed in is returned through the internal execution of this method.

_ Set () method: This method is used to set values for private member attributes. There are two parameters. The first parameter is the attribute name for the set value, the second parameter is the value to be set for the attribute, with no return value. This method does not need to be called manually. It is automatically called when private property values are directly set. The private property is encapsulated. If no _ set () this method is not allowed, for example, "$ this-> name = 'hangsan', this will cause an error, but if you add _ set ($ property_name, $ value) This method is automatically called when a value is directly assigned to a private attribute, passing the attribute such as name to $ property_name, pass the value "zhangsan" to $ value. The value can be assigned through the execution of this method. In order not to pass in invalid values, you can also make a judgment in this method.

11. Inheritance Letter of the class

Inheritance is one of the important features of php5 object program design. It refers to the creation of a new derived class that inherits data and functions from one or more previously defined classes, in addition, you can redefine or add new data and functions to establish a class hierarchy or level. Simply put, inheritance is the mechanism by which child classes automatically share the data structure and method of the parent class. This is a relationship between classes.

The Inheritance Mechanism allows you to use existing data types to define new data types. The defined new data type not only has the newly defined members, but also has the old members. We call the existing class used to derive the new class as the base class, also known as the parent class and super class. A new class derived from an existing class is called a derived class, or a subclass.

In software development, the inheritance of classes makes the software open and scalable. This is an effective method for information organization and classification. It simplifies the workload of object and class creation, added code reusability. Inheritance is used to provide a standard class level structure. Through the inheritance relationship of classes, public features can be shared, improving the reusability of software.

PHP and Java do not have many inheritance, but only single inheritance. That is to say, a class can only inherit data from one class directly. This is what we call single inheritance.

Subclass uses the "extends" keyword to inherit the parent class

12. Reload the New Method

When learning PHP, you will find that methods in PHP cannot be reloaded. The so-called method reload means defining the same method name, you can access different methods with the same method name by using "different number of parameters" or "different parameter types. However, because PHP is a weak language, different types of data can be received in method parameters, and PHP methods can receive parameters of an indefinite number, therefore, it is not true to call different methods with different method names by passing different numbers of parameters. So there is no method to overload in PHP. It cannot be overloaded, that is, you cannot define methods with the same method name in your project. In addition, because PHP does not have the concept of name sub-space, the same name method cannot be defined on the same page and the contained page, you cannot define a method with the same name as the method provided by PHP. Of course, you cannot define a method with the same name in the same class.

The new method of overloading is that the subclass overwrites the existing methods of the parent class. Although the methods of the same name cannot be defined in PHP, in the two classes of the parent-child relationship, we can define methods with the same name as the parent class in the subclass, so that the inherited methods in the parent class are overwritten.

In actual development, it is impossible for a method to have one or several pieces of code. For example, the "say ()" method in the "Person" class contains 100 pieces of code, if we want to add a little functionality to this method to preserve the original functions, we need to rewrite the original 100 pieces of code and add several extended pieces of code. This is good, in some cases, the methods in the parent class cannot see the original code. How do you rewrite the original code at this time? We can also solve this problem by calling the override method in the parent class in the subclass method, that is to say, you can add your own functions to the original functions of the method to be overwritten by the parent class in the subclass method in two ways:

One is to use the "Class Name:" of the parent class to call the override method in the parent class;

One is to use the "parent:" method to call the method that is overwritten in the parent class;

You may find that the code you write accesses the variables and functions of the parent class. This is especially true if the subclass is very refined or the parent class is very specialized. Do not use the name of the parent class in the code. You should use the special name parent, which refers to the name of the parent class that the subclass refers to in the extends declaration. This avoids the use of the parent class name in multiple places. If the inheritance tree needs to be modified during implementation, simply modify the part declared by extends in the class.

Similarly, if the constructor is not declared in the subclass, you can also use the constructor in the parent class. If a new constructor is defined in the subclass, it will overwrite the constructor in the parent class, you can assign values to all attributes using the new constructor in the same way.

Class Student extends Person

{

Var $ school; // attributes of the student's school

Function _ construct ($ name, $ sex, $ age, $ school)

{

// Use the method in the parent class to assign values to the original attribute

Parent: :__ construct ($ name, $ sex, $ age );

$ This-> school = $ school;

}

// How the student learns

Function study ()

{

Echo "My name is:". $ this-> name. "I'm learning". $ this-> school ."

";

}

// This person can talk about his/her attributes.

Function say ()

{

Parent: say ();

// Add your own functions

Echo "My age is:". $ this-> age. "I am at". $ this-> school.

";

}

}

13. Access type

Public modifier. No access restriction is imposed on members in the class. All external members can access (read and write) This class member (including member attributes and member methods ), in all versions prior to PHP5, PHP class members are all public, and in PHP5, if the class members do not specify the member access modifier, it will be treated as public.

Private modifier, which is defined as a private member. it is visible to all members in the same class, that is, there is no access restriction; however, external code of this class is not allowed to change or even read operations, and the subclass of this class cannot access private modified members.

Protected protects the member modifier. The member modified as protected cannot be accessed by the class's external code. However, the subclass of this class has access permissions and can perform read and write operations on attributes and methods. The external code of this subclass, including its subclass, does not have the permission to access its attributes and methods.

Note that the method access permission of the subclass must not be lower than the access permission of the parent class override method, that is, it must be higher than or equal to the access permission of the parent class method.

For example, if the access permission of the parent class method is protected, the permissions to be overwritten in the subclass must be protected and public, if the method of the parent class is public, the method to be overwritten in the subclass can only be public. In short, the method in the subclass is always higher than or equal to the access permission of the parent class to be overwritten.

14. Application of final keywords

This keyword can only be used to define classes and methods. The final keyword cannot be used to define Member attributes. Because final is a constant, we use define () to define constants in PHP () function, so you cannot use final to define Member attributes.

Classes marked with final key cannot be inherited;

The final key TAG method cannot be overwritten by the quilt class. It is the final version.

15. Use of static and constant keywords

Static keywords are used to describe member attributes and member methods in a class. static members can restrict external access because static members belong to a class and do not belong to any object instance, it is the space allocated when the class is loaded for the first time. Other classes cannot be accessed. They only share instances of the class and can protect the members of the class to a certain extent;

From the memory perspective, we can analyze that the memory is logically divided into four sections, where the object is placed in the heap memory, and the object reference is placed in the stack memory, static members are placed in the "initialize static segments". When the class is loaded for the first time, each object in the heap memory can be shared.

Static variables of the class are very similar to global variables and can be shared by all class instances. Static Methods of the class are also the same, similar to global functions.

Static members are created when the class is loaded for the first time. Therefore, static members can be accessed by using class names without objects outside the class. As mentioned above, if a static member is shared by every instance object of this class, can we use the object to access static members in the category? We can see that static members do not exist within each object, but each object can be shared. Therefore, if we use an object to access members, this attribute is not defined, objects that cannot access static members are used. In other object-oriented languages, for example, Java can access static members using objects, if PHP can use objects to access static members, we should try not to use them, because static members are designed to access the members by class names during project creation.

Static Methods in the class can only be static attributes of the category. Static Methods in the class cannot be non-static members of the category. The reason is very simple, to access other members of this class in the method of this class, we need to use the reference $ this, and the reference pointer $ this represents the object that calls this method, we have mentioned that static methods do not need to be called by objects, but are accessed by class names, so there is no object at all, and there is no reference to $ this, without the $ this reference, the non-static members in the category cannot be accessed because the static members in the class can be accessed without objects, therefore, the static method in the class can only have the static attribute of the category class, that is, $ this does not exist. to access other static members in the static method, we use a special class "self "; self is similar to $ this, except that self represents the class of this static method. Therefore, in a static method, you can use the "Class Name" of the class where this method is located, or use "self" to access other static members. If there are no special circumstances, we usually use the latter,

That is, the "self: Member attributes" method.

Class Person

{

// The following table lists the static member attributes of a person.

Public static $ myCountry = "China ";

 

// This is the static member method of a person. access other static members through self.

Public static function say ()

{

Echo "I am". self: $ myCountry ."

";

}

}

// Access static methods

Person: say ();

?>

You can access static members in non-static methods. Of course, you can also use the class name or "self :: the form of member attributes ".

Const is a key word for defining constants. Defining constants in PHP uses the "define ()" function, but defining constants in a class uses the "const" keyword, similar to # define in C. If the value of define is changed in the program, an error occurs, the access method of member attributes modified with "const" is similar to that of member access modified with "static". The "Class Name" is also used, and the "self" keyword is used in the method. However, you do not need to use the '$' symbol or use an object to access it.

<? Php

Class MyClass

{

// Define a constant

Const constant = 'constant value ';

Function showConstant (){

Echo self: constant. "\ n"; // use self for access. Do not add "$"

}

}

Echo MyClass: constant. "\ n"; // use the class name for access without adding "$"

$ Class = new MyClass ();

$ Class-> showConstant ();

// Echo $ class: constant; is not allowed

?>

16. _ toString () method

As we have mentioned earlier, the methods for declaring the method name "--" in the class (provided by PHP) are all automatically called for execution at different times, the "_ toString ()" method is also automatically called, which is automatically called when the object is directly referenced. We have mentioned that object reference is a pointer, for example: in "$ p = new Person ()", $ p is a reference. We cannot use echo to directly output $ p, which will output "Catchable fatal error: object of class Person cocould not be converted to string. If you define the "_ toString ()" method in the class, when you directly output the Object reference, instead of generating errors, the "_ toString ()" method is automatically called to output the characters returned from the "_ toString ()" method,

Therefore, the "_ toString ()" method must have a return value (return Statement ).

17. Clone object

Sometimes we need to use two or more identical objects in a project. If you re-create an object using the "new" keyword, assign the same attribute to it, this method is cumbersome and error-prone. Therefore, it is necessary to clone an identical object based on an object. After cloning, the two objects do not interfere with each other.

In PHP5, we use the "clone" keyword to clone the object;

PHP5 defines a special method named "_ clone ()", which is automatically called during object cloning and uses "_ clone () the method creates an object with the same attributes and methods as the original object. To change the content of the original object after cloning () override the original attributes and methods. The "_ clone ()" method can have no parameters. It automatically contains two pointers: $ this and $ that [A3]. $ this points to the duplicate, and $ that points to the original;

18. _ call handle call errors

In Program Development,If the called method does not exist when an object is used to call an internal method of the object, an error occurs in the program and the program cannot be executed after it exits. Then, when the program calls a method that does not exist inside the object, it prompts that the method we call and the parameters we use do not exist, but the program can continue to execute, in this case, we need to use the "_ call ()" method that is automatically called when a non-existing method is called ()".

<? Php

// This is a test class with no attributes or methods in it

Class Test

{

// The method automatically called when a non-stored method is called. The first parameter is the method name, and the second parameter is the array parameter.

Function _ call ($ function_name, $ args)

{

Print "the function you call: $ function_name (parameter :";

Print_r ($ args );

Echo "does not exist! <Br> \ n ";

}

}

// Generate a Test Class Object

$ Test = new Test ();

// Call a method that does not exist in the object

$ Test-> demo ("one", "two", "three ");

// The program will not exit and can be executed here

Echo "this is a test <br> ";

?>

19. Abstract methods and abstract classes

In OOP, a class can have one or more sub-classes, and each class has at least one public method as an external code to access its interface. Abstract methods are introduced to facilitate inheritance. Let's take a look at the definition of abstract classes and abstract methods and then describe their usage.

What is an abstract method? The method defined in the class without a method body is an abstract method. The so-called "No method body" means that there is no braces or content in the method declaration, instead, add a semicolon to the end of the method name during declaration, and add the keyword "abstract" to declare the abstract method;

For example:

Abstract function fun1 ();

Abstract function fun2 ();

In the above example, there is an abstract method "fun1 ()" and "fun2 ()" modified by abstract without a method body. Do not forget that there is a semicolon after the abstract method; so what is an abstract class? As long as a method in a class is an abstract method, this class should be defined as an abstract class, and the abstract class should also be modified using the "abstract" keyword; abstract classes can contain non-abstract methods and member attributes. However, if a method is an abstract method, this class must be declared as an abstract class and modified using "abstract.

For example:

Abstract class Demo

{

Var $ test;

Abstract function fun1 ();

Abstract function fun2 ();

Function fun3 ()

{

....

}

}

The most important thing is that abstract classes cannot generate instance objects, so they cannot be used directly. We have mentioned many times that classes cannot be used directly. We use objects instantiated by classes, so abstract classes cannot generate instance objects. What is the purpose of declaring abstract classes? Abstract methods are used as templates for subclass overloading. Defining an abstract class is equivalent to defining a specification that requires subclass compliance. After the subclass inherits the abstract class, implement the abstract methods in the abstract class according to the requirements of the subclass. The subclass must implement all the abstract methods in the parent class. Otherwise, there are still abstract methods in the subclass, so the subclass or abstract class still cannot instantiate the object. Why do we have to inherit from the abstract class? Sometimes, to implement some functions, we must inherit from the abstract class; otherwise, you cannot implement these functions. If the abstract class is inherited, we must implement the abstract methods in the class;

20. php5 Interface Technology

PHP, like most object-oriented programming languages, does not support multiple inheritance. that is to say, each class can only inherit one parent class. to solve this problem, PHP introduces interfaces. The interface idea is to specify a series of methods that must be implemented by a class that implements the interface. an interface is a special abstract class, and an abstract class is a special class, so an interface is also a special class. Why is an interface a special abstract class? If all the methods in an abstract class are abstract methods, we use the "interface" for another declaration method. That is to say, all the methods in the interface must be declared as abstract methods, in addition, variables cannot be declared in the interface, and all the Members in the interface have the public permission. Therefore, subclass must also use the public permission to implement it.

When declaring a class, the keyword we use is "class", while the interface is a special class and the keyword used is "interface ";

Class Definition: class name {... }, Interface declaration: interface name {...}

All methods in the interface are abstract methods. Therefore, when declaring an abstract method, you do not need to use the "abstract" keyword like an abstract class. This keyword is added by default, in addition, the "public" access permission in the interface can also be removed, because it is public by default, because all the members in the interface are public, therefore, we cannot use the "private" and "protected" permissions for the Members in the interface. public or default permissions are required. In addition, we also declare a constant "constant" in the interface. Because variable members cannot be used in the interface, we need to use the const keyword for declaration.

Because an interface is a special abstract class, all the methods in it are abstract methods, so the interface cannot generate instance objects; it is also a standard, and all abstract methods need to be implemented by subclasses.

We can use the "extends" keyword to let one interface inherit from another interface. We define the subclass of the interface to implement all the abstract methods in the interface. The keyword used is "implements ", instead of the "extends" we mentioned earlier ";

We can also use abstract classes to implement partial abstract methods in Interfaces. However, to instantiate an object, this abstract class must have a subclass to implement all its abstract methods;

As we have mentioned earlier, PHP is a single inheritance. A class can only have one parent class, but a class can implement multiple interfaces, which is equivalent to a class complying with multiple specifications, just as we must not only abide by national laws, but also comply with school rules if we are in school;

21. Application of Polymorphism

Polymorphism is one of the three major features of another surface object except encapsulation and inheritance. In my opinion, although polymorphism can be achieved in PHP, but compared with the object-oriented languages c ++ and Java, polymorphism is not so prominent, because PHP itself is a weak language, there is no problem in converting a parent class object to a subclass object or a subclass object to a parent class object, so the application of polymorphism is not so obvious; polymorphism refers to the ability of a program to process multiple types of objects, such as working at a company, paying a monthly financial account, and sending a salary in the same way, different employees in the company or employees in different positions are issued through this method, but the salaries are different. Therefore, there are many forms of the same wage payment method. For Object-oriented Programs, polymorphism is to assign a subclass object to the parent class for reference, and then call the parent class method to execute the method that the subclass overrides the parent class, however, PHP is of a weak type, and object references are the same regardless of the parent class or subclass references.

22. serialize objects

Sometimes an object needs to be transmitted over the network. To facilitate transmission, the entire object can be converted into a binary string and restored to the original object when it reaches the other end, this process is called serialization, just as we want to ship a car to the United States through a ship. because the size of the car is large, we can split the car into small parts, then we ship these parts to the United States in a round, and then assemble them into the United States and return them to the automobile.

There are two cases where we must serialize objects. The first case is to serialize objects when transmitting an object over the network, the second case is to use serialization when writing objects into a file or database.

There are two steps of serialization. One is serialization, that is, converting an object into a binary string. We use the serialize () function to serialize an object, and the other is deserialization, it is to convert the binary string converted by the object into an object. We use the unserialize () function to deserialize an object.

The parameter of the serialize () function in PHP is the object name, and the returned value is a string. The meaning of the string returned by Serialize () is fuzzy. Generally, this string is not parsed to obtain the object information, we only need to upload the returned string to the other end of the network or save it to the component.

In PHP, The unserialize () function is used to deserialize objects. The parameter of this function is the return value of the serialize () function, and the output is of course a re-organized object.

<?

Class Person

{

// The following are the member attributes of a person.

Var $ name; // name of a person

Var $ sex; // gender of a person

Var $ age; // age of a person

// Define a constructor parameter to assign values to the attribute name $ name, gender $ sex, and age $ age.

Function _ construct ($ name = "", $ sex = "", $ age = "")

{

$ This-> name = $ name;

$ This-> sex = $ sex;

$ This-> age = $ age;

}

// This person can talk about his/her attributes.

Function say ()

{

Echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age. "<br> ";

}

}

$ P1 = new Person ("Zhang San", "male", 20 );

$ P1_string = serialize ($ p1); // serializes an object and returns a string

Echo $ p1_string. "<br>"; // serialized strings are not parsed.

$ P2 = unserialize ($ p1_string); // concatenates A serialized string to form an object. $ p2

$ P2-> say ();

?>

Output result of the preceding example:

O: 6: "Person": 3: {s: 4: "name"; s: 4: "Zhang San"; s: 3: "sex"; s: 2: "male"; s: 3: "age"; I: 20 ;}

My name is John. Gender: male. My age is: 20.

There are two magic methods _ sleep () and _ wakeup () in php5. When the object is serialized, A _ sleep () is called () before going to bed, the system automatically calls another function _ wakeup () of PHP when waking up again, that is, the binary string re-forms an object (), do some actions that the object will do when it wakes up.

The _ sleep () function does not accept any parameters, but returns an array containing serialized attributes. Attributes contained at the end will be ignored during serialization. If the _ sleep () method is not available, PHP will save all attributes.

<?

Class Person

{

// The following are the member attributes of a person.

Var $ name; // name of a person

Var $ sex; // gender of a person

Var $ age; // age of a person

// Define a constructor parameter to assign values to the attribute name $ name, gender $ sex, and age $ age.

Function _ construct ($ name = "", $ sex = "", $ age = "")

{

$ This-> name = $ name;

$ This-> sex = $ sex;

$ This-> age = $ age;

}

// This person can talk about his/her attributes.

Function say ()

{

Echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age. "<br> ";

}

// Specify the $ name and $ age values in the returned array for serialization, ignoring the attribute $ sex not in the array

Function _ sleep (){

$ Arr = array ("name", "age ");

Return ($ arr );

}

// When the object is regenerated, the value of $ age is 40.

Function _ wakeup (){

$ This-> age = 40;

}

}

$ P1 = new Person ("Zhang San", "male", 20 );

// Serializes an object and returns a string. The _ sleep () method is called to ignore the attribute $ sex that is not in the array.

$ P1_string = serialize ($ p1 );

Echo $ p1_string. "<br>"; // serialized strings are not parsed.

$ P2 = unserialize ($ p1_string); // form an object through deserialization. $ p2 is assigned a value again. $ age is 40.

$ P2-> say ();

?>

The output value of the preceding example is:

O: 6: "Person": 2: {s: 4: "name"; s: 4: "Zhang San"; s: 3: "age"; I: 20 ;}

My name is Zhang San Gender: My age is: 40

23. automatically load the class

Many developers create a PHP source file for each class definition when writing object-oriented applications. A big headache is that you have to write a long list of contained files at the beginning of each script (each class has one file.

In a software development system, it is impossible to write all classes in one PHP file. When one PHP file needs to call the classes declared in another file, you need to introduce this file through include. However, when there are many file projects, it is a headache to include all the files of the required classes one by one, so can we use any classes, what about importing the PHP file where this class is located? This is the automatic loading class we will talk about here.

In PHP 5, A _ autoload () function can be defined, which is automatically called when trying to use a class that has not been defined. by calling this function, before a PHP error fails, the script engine has the last chance to load the required class. A parameter received by the _ autoload () function is the class name of the class you want to load, therefore, when you create a project, you need to follow certain rules when organizing the file name of the class, it is best to center the class name, or you can add a uniform prefix or suffix to form a file name, for example, xxx_classname.php, classname_xxx.php, and classname. php, etc.

In this example, we try to load the MyClass1 and MyClass2 classes in the MyClass1.php and MyClass2.php files respectively.

<? Php

Function _ autoload ($ classname)

{

Require_once $ classname. '. php ';

}

// The MyClass1 class does not automatically call the _ autoload () function. The input parameter "MyClass1"

$ Obj = new MyClass1 ();

// The MyClass2 class does not automatically call the _ autoload () function. The input parameter "MyClass2"

$ Obj2 = new MyClass2 ();

?>

[A1] it is out of date. Although no error is reported, it is out of date.

[A2] 64-bit is a system type

[A3] $ that cannot be used at all

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.