1. The concept of facial objects
Object Oriented Programming (OOP, object-oriented programming) is a computer programming architecture. One of the basic principles of OOP is that a computer program is composed of a single unit or object that can function as a subroutine. OOP achieves the three goals of software engineering: reusability, flexibility, and scalability. In order to realize the overall operation, each object can receive information, process data and send information to other objects. Object-oriented has always been a hot topic in the field of software development. First of all, object-oriented is in line with the general rules of how humans look at things. Secondly, the use of object-oriented methods allows each part of the system to perform its duties and perform its duties. This opens the door for programmers to write code that is simpler, easier to maintain, and more reusable. Some people say that PHP is not a true object-oriented language, and this is true. PHP is a hybrid language, you can use OOP or traditional procedural programming. However, for large projects, you may need to use pure OOP to declare classes in PHP, and only use objects and classes in your project. I won’t go into detail about this concept because the main reason why many people and friends stay away from object-oriented programming is that they can’t understand the object-oriented concept when they are exposed to it, so they don’t want to learn it. Let the readers understand the concept after reading the overall content.
2. What is a class, what is an object, and the relationship between classes and objects
Concept of class: A class is a collection of objects with the same properties and services. It provides a unified abstract description for all objects belonging to this class, which includes two main parts: properties and services. In object-oriented programming languages, a class is an independent program unit. It should have a class name and include two main parts: attribute description and service description.
The concept of object: An object is an entity used to describe objective things in the system. It is a basic unit that constitutes the system. An object consists of a set of properties and a set of services that operate on the set of properties. From a more abstract perspective, an object is an abstraction of something in the problem domain or implementation domain, which reflects the information that needs to be saved and the role that the thing plays in the system; it is an encapsulation of a set of attributes and a set of services that have the authority to operate on these attributes. The objective world is composed of objects and the connections between objects.
The relationship between classes and objects is like the relationship between molds and castings. The instantiation result of a class is an object, and the abstraction of a type of object is a class. A class describes a group of objects with the same characteristics (properties) and the same behavior (methods).
The above are probably their definitions. Maybe you are a friend who is new to face-to-face objects. Don’t be confused by the concepts. Let me give you an example. If you go to Zhongguancun and want to buy a few assembled PCs, what will be your first step when you get there? Will the installation engineer sit with you and complete an installation configuration list with you based on the information you provided? This configuration sheet can be imagined as a category. It is just a piece of paper, but it records the information of the PC you want to buy. If you use this configuration sheet to buy 10 machines, then these 10 machines will all be composed according to this configuration sheet. Therefore, these 10 machines are of the same type, or they can be said to be the same category. So what is an object? The instantiation result of a class is an object. The machine configured (instantiated) using this configuration sheet is an object. It is an entity that we can operate. 10 machines, 10 objects. Each machine is independent, which only means that they are of the same type. Any action on one machine will not affect the other 9 machines. However, if I modify the class, that is, add one or less accessories to this configuration list, then all 9 installed machines will be changed. This is the relationship between classes and objects (the instantiation result of a class is an object).
3. What is object-oriented programming?
Not to mention his concept, if you want to build a computer classroom, you must first have a room with N computers, N desks, N chairs, whiteboards, projectors, etc. What are these? As we just said, these are objects, entities that can be seen. It can be said that the units of this computer classroom are these physical objects. They together make up this computer classroom. So we are doing programs. What does this have to do with object-oriented? Developing a system program is similar to building a computer classroom. You abstract each independent functional module into a class-forming object. The system is composed of multiple objects. These objects can all interact with each other by receiving information, processing data, sending information to other objects, and so on. This constitutes an object-oriented program.
4. How to abstract a class?
As mentioned above, the unit of an object-oriented program is an object, but an object is instantiated by a class, so the first thing we have to do is how to declare a class. It is easy to make a class, as long as you master the basic programming grammar definition rules. So what is the difficulty? How many classes and objects should be used in a project, where the class should be defined, what kind of class is defined, how many objects are instantiated by this class, how many attributes are there in the class, how many methods are there, etc. This requires readers to analyze, design and summarize practical problems in actual development.
Class definition:
class class name {
}
Use the keyword class followed by a class name you want and a pair of curly brackets. In this way, the structure of a class is defined. Just write the code in it. But what is written in it? What can I write? How to write a complete class? As mentioned above, the purpose of using a class is to make it instantiate objects for us to use. This requires knowing what kind of object you want. Like the installation configuration sheet we mentioned above, whatever is written on the installation configuration sheet will be what you install on the machine. For example, a person is a target. How do you recommend a person you like to your leader? Of course, the more detailed the better:
First, you will introduce the person's name, gender, age, height, weight, phone number, home address, etc.
Then, you have to introduce what this person can do, whether he can drive, speak English, use a computer, etc.
As long as you introduce more, others will know more about this person. This is our description of a person. Now let's summarize, all objects we use to describe are similar. From the description of people above, making a class is divided into two parts from the definition point of view. The first is static description, and the second is dynamic description. Static description is what we call attributes. As we saw above, a person's name, gender, age, height, weight, phone number, home address, etc. Dynamically speaking, it is the function of this human object. For example, this person can drive, speak English, can use a computer, etc. When abstracted into a program, we write the dynamic as a function or method. 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 person { member attributes: name, gender, age, height, weight, phone number, home address member method: can drive, can speak English, can use a computer }
property:
By using the keyword "var" in the class definition to declare variables, the attributes of the class are created. Although initial values can be given when declaring member attributes, it is not necessary to set initial values for member attributes when declaring a class. For example, if a person's name is assigned to "Zhang San", then dozens of people will be created using this class instance, and these dozens of people will be called Zhang San, so there is no need. We can just give the initial values to the member attributes after the object is created from the instance.
Such as: var $somevar;
Method (member function):
By declaring a function in a class definition, you create a method of the class.
Such as: function somefun (parameter list)
{ … … }
The above is a declaration of a class, a class declared from attributes and methods, but it is best not to assign initial values to member attributes when declaring them, because the person class we make is a description information, and we will use it to instantiate objects in the future. For example, if we instantiate 10 human objects, then each of these 10 people will have a different name, gender, and age, so it is best not to assign initial values to member attributes here, but to assign values to each object separately.
You can use the same method to create the class you want. As long as you can use attributes and methods to describe entities, you can define them as classes and instantiate objects.
In order to strengthen your understanding of classes, let's make another class, a shape class. The range of shapes is a bit wider, so let's make a rectangle. Let's analyze it first. Think about it from two aspects. What are the attributes of a rectangle? What are the functions of a rectangle?
class rectangle { //Attributes of the rectangle The length of the rectangle; The width of the rectangle; //Methods of the rectangle The perimeter of the rectangle; The area of the rectangle; } If you use this class to create multiple rectangular objects, each rectangular object has its own length and width, and you can calculate its own perimeter and area.
Let’s stop here with the class declaration! !
5. How to instantiate objects
We said above that the unit of an object-oriented program is an object, but objects are instantiated through classes. Now that our class has been declared, the next step is to instantiate the object.
After defining the class, we use the new keyword to generate an object.
$ObjectName = new ClassName();
$p1=new Person();
This code is the process of generating instance objects through classes. $p1 is the name of the object we instantiate. Similarly, $p2 and $p3 are also the names of the objects we instantiate. A class can instantiate multiple objects, and each object is independent. The above code is equivalent to instantiating 3 people. There is no connection between each person. It can only mean that they are all human beings. Each person has his own name. Attributes of gender and age, everyone has a way of talking and walking. As long as they are member attributes and member methods reflected in the class, the instantiated object will contain these attributes and methods.
In PHP, like integers and floating-point types, objects are also a data class. They are used to store different types of data. They must be loaded into memory for use during runtime. So how are objects reflected in memory? Logically speaking, memory is generally divided into 4 segments, stack space segment, heap space segment, code segment, initialization static segment. Different declarations in the program are placed in different memory segments. The stack space segment is a place where data types that occupy the same space length and occupy small space are stored, such as integers 1, 10, 100, 1000, 10000, 100000 and so on, the space occupied in the memory is the same length, both are 64 bits and 4 bytes. So where should data of a data type whose data length is variable and takes up a lot of space be placed in that memory segment? Such data is placed in the heap memory. Stack memory can be directly accessed, while heap memory cannot be directly accessed. Our object is a large data type and takes up space of a variable length, so the object is placed in the heap, but the object name is placed in the stack, so that the object can be used through the object name.
$p1=new Person();
For this code, $p1 is the object name in the stack memory, and new Person() is the real object in the heap memory. Please see the figure below for details:
As can be seen from the picture above, $p1=new Person(); the right side of the equal sign is the real object instance. In the entity in the heap memory, there are 3 times of new Person() in the picture above, so 3 spaces will be opened in the heap and 3 instance objects will be generated. Each object is independent of each other and uses its own space. In PHP, as long as a new keyword appears, an object will be instantiated and a space of its own will be created in the heap.
Each instance object in the heap stores attributes. For example, the instance objects in the heap now store name, gender, and age. Each attribute in turn has an address.
$p1=new Person(); The right side of the equal sign $p1 is a reference variable. The first address of the object is assigned to the reference variable "$p1" through the assignment operator "=", so $p1 is the variable that stores the first address of the object. $p1 is placed in the stack memory. $p1 is equivalent to a pointer pointing to the object in the heap, so we can operate the object through the reference variable $p1. Usually we also call the object reference an object.
6. How to use members in the object
As seen above, there are two types of members in PHP objects: member attributes and member methods. We can now declare the object. $p1=new Person(); How to use the members of the object? If you want to access the members of an object, you need to use a special operator "->" to complete the access of the object members:
Object->Properties $p1->name; $p2->age; $p3->sex;
Object->Method $p1->say(); $p2->run();
Such as the following examples:
name=”张三”; $p1->sex=”男”; $p1->age=20; //下面三行是访问$p1对象的属性 echo “p1对象的名子是:”.$p1->name.”
”; echo “p1对象的性别是:”.$p1->sex.”
”; echo “p1对象的年龄是:”.$p1->age.”
”; //下面两行访问$p1对象中的方法 $p1->say(); $p1->run(); //下面三行是给$p2对象属性赋值 $p2->name=”李四”; $p2->sex=”女”; $p2->age=30; //下面三行是访问$p2对象的属性 echo “p2对象的名子是:”.$p2->name.”
”; echo “p2对象的性别是:”.$p2->sex.”
”; echo “p2对象的年龄是:”.$p2->age.”
”; //下面两行访问$p2对象中的方法 $p2->say(); $p2->run(); //下面三行是给$p3对象属性赋值 $p3->name=”王五”; $p3->sex=”男”; $p3->age=40; //下面三行是访问$p3对象的属性 echo “p3对象的名子是:”.$p3->name.”
”; echo “p3对象的性别是:”.$p3->sex.”
”; echo “p3对象的年龄是:”.$p3->age.”
”; //下面两行访问$p3对象中的方法 $p3->say(); $p3->run(); ?>
From the above example, we can see that only the members in the object must be accessed using the object->property and object->method forms. There is no second way to access the members in the object.
7. The use of special reference "$this"
Now we know how to access members in an object through "Object -> Members", which is a form of accessing members in an object from outside the object. So what should we do if I want to let the methods in the object access the properties of this object inside the object, or the methods in the object call other methods of this object? Because all members in the object must be called by objects, including calls between internal members of the object, PHP provides me with a reference to the object $this. Each object has a reference to the object $this to represent the object to complete the call of the internal members of the object. The original meaning of this is "this". In the above example, we instantiate three instance objects $P1, $P2, $P3, there is one $this in each of these three objects, representing objects $p1, $p2, and $p3 respectively.
We can see from the above figure that $this is the reference that represents the object inside the object. The same method is used to call members of this object inside the object and to call members of the object outside the object.
$this->Properties $this->name; $this->age; $this->sex;
$this->method $this->say(); $this->run();
Modify the above example so that everyone states their name, gender, and age:
name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } function run() //这个人可以走路的方法 { echo '这个人在走路'; } } $p1=new Person(); //创建实例对象$p1 $p2=new Person(); //创建实例对象$p2 $p3=new Person(); //创建实例对象$p3 //下面三行是给$p1对象属性赋值 $p1->name='张三'; $p1->sex='男'; $p1->age=20; //下面访问$p1对象中的说话方法 $p1->say(); //下面三行是给$p2对象属性赋值 $p2->name='李四'; $p2->sex='女'; $p2->age=30; //下面访问$p2对象中的说话方法 $p2->say(); //下面三行是给$p3对象属性赋值 $p3->name='王五'; $p3->sex='男'; $p3->age=40; //下面访问$p3对象中的说话方法 $p3->say(); ?>
The output is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40
Let’s analyze this method:
function say() //这个人可以说话的方法 { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } There is a say() method in the three objects $p1, $p2 and $p3. $this represents these three objects respectively, calls the corresponding attributes and prints out the value of the attributes. This is the way to access the object attributes inside the object. If the run() method is called in the say() method, it is also possible to use the $this->run() method in the say() method to complete the call.
8.Construction method and destruction method
Most classes have a special method called a constructor. When an object is created, it will automatically call the constructor, that is, when the new keyword is used to instantiate the object, the constructor will be automatically called.
The declaration of a constructor is the same as the declaration of other operations, except that 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. This can still be used in PHP5, but few people use it now. The advantage of this is that the constructor can be made independent of the class name. When the class name changes, there is no need to change the corresponding constructor name. For backward compatibility, if there is no method named __construct() in a class, PHP will search for a constructor 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, but the constructor will only be called once every time an object is created. This method cannot be called actively, so it is usually used to perform some useful initialization tasks. For example, the corresponding properties are assigned initial values when the object is created.
//创建一个人类 class Person { //下面是人的成员属性 var $name; //人的名子 var $sex; //人的性别 var $age; //人的年龄 //定义一个构造方法参数为姓名$name、性别$sex和年龄$age function __construct($name, $sex, $age) { //通过构造方法传进来的$name给成员属性$this->name赋初使值 $this->name=$name; //通过构造方法传进来的$sex给成员属性$this->sex赋初使值 $this->sex=$sex; //通过构造方法传进来的$age给成员属性$this->age赋初使值 $this->age=$age; } //这个人的说话方法 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } } //通过构造方法创建3个对象$p1、p2、$p3,分别传入三个不同的实参为姓名、性别和年龄 $p1=new Person(“张三”,”男”, 20); $p2=new Person(“李四”,”女”, 30); $p3=new Person(“王五”,”男”, 40); //下面访问$p1对象中的说话方法 $p1->say(); //下面访问$p2对象中的说话方法 $p2->say(); //下面访问$p3对象中的说话方法 $p3->say(); ?> The output is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40
Destructor:
The opposite of a constructor is a destructor. The destructor is a newly added content of PHP5. There is no destructor in PHP4. The destructor allows you to perform some operations or complete some functions before destroying a class, such as closing files, releasing result sets, etc. The destructor will be 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 memory. Similar to the name of the constructor, the name of a class's destructor must be __destruct(). The destructor cannot take any parameters.
Format: function __destruct ( ) { … … }
//创建一个人类 class Person { //下面是人的成员属性 var $name; //人的名子 var $sex; //人的性别 var $age; //人的年龄 //定义一个构造方法参数为姓名$name、性别$sex和年龄$age function __construct($name, $sex, $age) { //通过构造方法传进来的$name给成员属性$this->name赋初使值 $this->name=$name; //通过构造方法传进来的$sex给成员属性$this->sex赋初使值 $this->sex=$sex; //通过构造方法传进来的$age给成员属性$this->age赋初使值 $this->age=$age; } //这个人的说话方法 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } //这是一个析构函数,在对象销毁前调用 function __destruct() { echo “再见”.$this->name.”
”; } } //通过构造方法创建3个对象$p1、p2、$p3,分别传入三个不同的实参为姓名、性别和年龄 $p1=new Person(“张三”,”男”, 20); $p2=new Person(“李四”,”女”, 30); $p3=new Person(“王五”,”男”, 40); //下面访问$p1对象中的说话方法 $p1->say(); //下面访问$p2对象中的说话方法 $p2->say(); //下面访问$p3对象中的说话方法 $p3->say(); ?> The output is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40
Goodbye Zhang San
Goodbye John Doe
Goodbye Wang Wu
9. Encapsulation
Encapsulation is one of the three major characteristics of object-oriented programming. Encapsulation is to combine the properties and services of an object into an independent and identical unit, and to hide the internal details of the object as much as possible. It contains two meanings: 1. Combining all the properties and services of the object to form an indivisible independent unit (i.e. object). 2. Information hiding, that is, hiding the internal details of the object as much as possible, forming a boundary (or forming a barrier) to the outside world, and retaining only a limited external interface to connect it with the outside.
The reflection of the principle of encapsulation in software is that it requires that parts other than the object cannot access the internal data (properties) of the object at will, thereby effectively avoiding the "cross-infection" of external errors, enabling software errors to be localized, and greatly reducing the difficulty of error detection and troubleshooting.
Let’s use an example to illustrate. Suppose a person’s object has attributes such as age and salary. Such personal privacy attributes are not accessible to others. If you don’t use encapsulation, others can get it if they want to know. However, if you encapsulate it, others will have no way to obtain the encapsulated attributes. Unless you tell it yourself, others will have no way to get it.
For example, personal computers have a password, and you don't want others to log in at will and copy and paste it into your computer. Also, for objects like people, the attributes of height and age can only be increased by oneself, and cannot be assigned values arbitrarily by others, etc.
Use the private keyword to encapsulate properties and methods:
Original members:
var $name; //Declarer’s name
var $sex; //Declare the person’s gender
var $age; //Declare the age of the person
function run(){…….}
Change to encapsulated form:
private $name; //Encapsulate the person's name using the private keyword
private $sex; //Encapsulate the person's gender using the private keyword
private $age; //Encapsulate the person's age using the private keyword
private function run(){......} //Use the private keyword to encapsulate a person's walking method
Note: As long as there are other keywords in front of the member attributes, the original keyword "var" must be removed.
Through private, human members (member attributes and member methods) can be encapsulated. The members in the encapsulation cannot be directly accessed outside the class, only within the object itself; the following code will generate an error:
class Person { //下面是人的成员属性 private $name; //人的名子,被private封装上了 private $sex; //人的性别, 被private封装上了 private $age; //人的年龄, 被private封装上了 //这个人可以说话的方法 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } //这个人可以走路的方法, 被private封装上了 private function run() { echo '这个人在走路'; } } //实例化一个人的实例对象 $p1=new Person(); //试图去给私有的属性赋值, 结果会发生错误 $p1->name='张三'; $p1->sex='男'; $p1->age=20; //试图去打印私有的属性, 结果会发生错误 echo $p1->name.”
”; echo $p1->sex.”
”; echo $p1->age.”
” //试图去打印私有的成员方法, 结果会发生错误 $p1->run(); The output is:
Fatal error: Cannot access private property Person::$name
Fatal error: Cannot access private property Person::$sex
Fatal error: Cannot access private property Person::$age
Fatal error: Cannot access private property Person::$name
Fatal error: Call to private method Person::run() from context ”
As can be seen from the above example, private members cannot be accessed externally, because private members can only be accessed within the object itself. For example, if the object $p1 wants to share its private attributes, it accesses the private attributes in the say() method. This is OK. (No access control is added, the default is public and can be accessed from anywhere)
//This person can speak in a way that speaks his or her own private properties. Private methods can also be accessed here.
function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; //在这里也可以访问私有方法 //$this->run(); }
Because the member method say() is public, we can call the say() method outside the class. Change the above code;
class Person { //下面是人的成员属性 private $name; //人的名子,被private封装上了 private $sex; //人的性别, 被private封装上了 private $age; //人的年龄, 被private封装上了 //定义一个构造方法参数为私有的属性姓名$name、性别$sex和年龄$age进行赋值 function __construct($name, $sex, $age) { //通过构造方法传进来的$name给私有成员属性$this->name赋初使值 $this->name=$name; //通过构造方法传进来的$sex给私有成员属性$this->sex赋初使值 $this->sex=$sex; //通过构造方法传进来的$age给私有成员属性$this->age赋初使值 $this->age=$age; } //This person can speak in a way that speaks his or her own private properties. Private methods can also be accessed here. function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } } //通过构造方法创建3个对象$p1、p2、$p3,分别传入三个不同的实参为姓名、性别和年龄 $p1=new Person(“张三”,”男”, 20); $p2=new Person(“李四”,”女”, 30); $p3=new Person(“王五”,”男”, 40); //下面访问$p1对象中的说话方法 $p1->say(); //下面访问$p2对象中的说话方法 $p2->say(); //下面访问$p3对象中的说话方法 $p3->say(); The output is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40
Because the constructor is a public method by default (the constructor should not be set to private), it can be accessed outside the class, so you can use the constructor to create objects. In addition, the constructor is also a function inside the class, so you can use the constructor to assign initial values to private properties. The Say() method is public by default, so it can be accessed from the outside to tell its own private properties.
From the above example, we can see that private members can only be used inside the class and cannot be directly accessed by outside the class. However, they are accessible inside the class, so sometimes we need to assign and read private properties outside the class, that is, provide some accessible interfaces to the outside of the class. In the above example, the constructor is a form of assignment, but the constructor only assigns when creating the object. If we already have an existing object and want to assign a value to this existing object, At this time, if you also use the constructor method to pass value, then a new object will be created, not the existing object. Therefore, we need to make some interfaces for private attributes that can be accessed by the outside. The purpose is to change and access the value of the attribute when the object exists. However, it should be noted that only the attributes that need to be changed externally can do this. The attributes that do not want to be accessed by the outside do not have such an interface. In this way, the purpose of encapsulation can be achieved. All functions are completed by the object itself, providing as few operations as possible to the outside world.
If you provide an interface outside the class, you can provide setting methods and get methods outside the class for private properties to operate the private properties. For example:
prvate $age; //私有的属性年龄 function setAge($age) //为外部提供一个公有设置年龄的方法 { if($age<0 || $age>130) //在给属性赋值的时候,为了避免非法值设置给属性 return; $this->age=$age; } function getAge() //为外部提供一个公有获取年龄的方法 { return($this->age); }
The above method is to set and get the value for a member attribute. Of course, you can also use the same method to assign and get the value for each attribute to complete the access work outside the class.
10. Application of the four methods __set() __get() __isset() __unset()
Generally speaking, always define class attributes as private, which is more in line with realistic logic. However, reading and assigning operations to attributes are very frequent, so in PHP5, two functions "__get()" and "__set()" are predefined to obtain and assign their attributes, as well as "__isset()" to check attributes and "__unset()" to delete attributes.
In the previous section, we set and obtained methods for each attribute. PHP5 provides us with special methods for setting and obtaining values for attributes, the two methods "__set()" and "__get()". These two methods do not exist by default, but we add them to the class manually. Like the constructor method (__construct()), it will only exist if it is added to the class. You can add these two methods in the following way. Of course, you can also add them according to your personal style:
//__get() method is used to get private properties function __get($property_name) { if(isset($this->$property_name)) { return($this->$property_name); }else { return(NULL); } } //__set() method is used to set private properties function __set($property_name, $value) { $this->$property_name = $value; }
__get() method: This method is used to obtain the private member attribute value. It has one parameter. The parameter is passed in the name of the member attribute you want to obtain, and the obtained attribute value is returned. This method does not need to be called manually. It is automatically called when the private attribute is directly obtained. Because private properties have been encapsulated, the value cannot be obtained directly (for example: "echo $p1->name" is wrong to obtain directly), but if you add this method to the class, when you use a statement such as "echo $p1->name" to directly obtain the value, the __get($property_name) method will be automatically called, and the property name will be passed to the parameter $property_name. Through the internal execution of this method, the value of the private property we passed in will be returned.
__set() method: This method is used to set values for private member attributes. It has two parameters. The first parameter is the name of the attribute you want to set the value for. The second parameter is the value you want to set for the attribute. There is no return value. This method also does not need to be called manually. It is automatically called when directly setting the value of a private property. Similarly, private properties have been encapsulated. If there is no __set() method, it is not allowed, such as: "$this->name='zhangsan'. This will cause an error. However, if you add the __set($property_name, $value) method to the class, it will be automatically called when directly assigning a value to a private property, and the property such as name will be passed to $property_name. Pass the value "zhangsan" to be assigned to $value, and achieve the purpose of assignment through the execution of this method. In order not to pass in illegal values, you can also make a judgment in this method:
Program execution result:
When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute.
When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute.
When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute.
When directly obtaining the private attribute value, the __get() method is automatically called.
Name: Zhang San
When directly obtaining the private attribute value, the __get() method is automatically called.
Gender: Male
When directly obtaining the private attribute value, the __get() method is automatically called.
Age: 20
If the above code does not add the __get() and __set() methods, the program will go wrong, because private members cannot be operated outside the class, and the above code helps us directly access the encapsulated private members by automatically calling the __get() and __set() methods.
__isset() method:
__unset() method:
11. Class inheritance
Inheritance, as one of the three important features of object-oriented, plays an extremely important role in the field of object-oriented. It seems that I have never heard of any object-oriented language that does not support inheritance. Inheritance is one of the important features of PHP5 object-oriented programming. It refers to creating a new derived class that inherits data and functions from one or more previously defined classes, and can redefine or add new data and functions, thereby establishing a class hierarchy or hierarchy. To put it simply, inheritance is a mechanism for subclasses to automatically share the data structures and methods of parent classes. This is a relationship between classes. When defining and implementing a class, you can do it on the basis of an existing class, take the content defined by the existing class as your own content, and add some new content. For example, you now have a class "person", which has two member attributes "name and age" and two member methods "talking method and walking method". If the program now needs a student class, because students are also people, students also have member attributes "name and age" and member methods "talking method and walking method". At this time, you can let the student class inherit this class. After inheritance, the student class will inherit all the attributes of the human being. There is no need for you to re-declare these member properties and methods, because the student class also has the properties of the school and the learning methods, so in the student class you make, in addition to the properties and methods inherited from the human being, plus the student-specific "school properties" and "learning methods", the declaration of a student class is completed. We can also call the inheritance letter "extension". From the above we can see that the student class extends the human being. On the basis of the original two attributes and two methods in human beings, one attribute and one method are added to extend a new student class.
Through the inheritance mechanism, existing data types can be used to define new data types. The new data type defined not only has the newly defined members, but also has the old members. We call existing classes used to derive new classes as base classes, also known as parent classes and super classes. A new class derived from an existing class is called a derived class, also called a subclass.
In software development, the inheritance of classes makes the software created open and extensible. This is an effective method of organizing and classifying information. It simplifies the workload of creating objects and classes and increases the reproducibility of the code. Using inheritance provides a standardized hierarchical structure of classes. Through the inheritance relationship of classes, public features can be shared, improving the reusability of software.
In C++ language, a derived class can be derived from one base class or multiple base classes. Inheritance derived from one base class is called single inheritance; inheritance derived from multiple base classes is called multiple inheritance.
But there is no multiple inheritance in PHP and Java languages, only single inheritance. That is to say, a class can only directly inherit data from one class. This is what we call single inheritance.
'; if(isset($this->$property_name)) { return($this->$property_name); }else { return(NULL); } } //__set()方法用来设置私有属性 function __set($property_name, $value) { echo '在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值
'; $this->$property_name = $value; } } $p1=new Person(); //直接为私有属性赋值的操作, 会自动调用__set()方法进行赋值 $p1->name='张三'; $p1->sex='男'; $p1->age=20; //直接获取私有属性的值, 会自动调用__get()方法,返回成员属性的值 echo '姓名:'.$p1->name.'
'; echo '性别:'.$p1->sex.'
'; echo '年龄:'.$p1->age.'
'; ?> For example:
Below is the abstraction of the "human" class
//定义一个“人”类做为父类 class Person { //下面是人的成员属性 var $name; //人的名子 var $sex; //人的性别 var $age; //人的年龄 //定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 function __construct($name, $sex, $age) { $this->name=$name; $this->sex=$sex; $this->age=$age; } //这个人可以说话的方法, 说出自己的属性 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } } 下面我们做一个”学生类”,如果不是用继承如下: //定义一个“人”类做为父类 class Student { //下面是人的成员属性 var $name; //人的名子 var $sex; //人的性别 var $age; //人的年龄 var $school; //学生所在学校的属性 //定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 function __construct($name=””, $sex=””, $age=””, $school=””) { $this->name=$name; $this->sex=$sex; $this->age=$age; $this->school=$school; } //这个人可以说话的方法, 说出自己的属性 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } //这个学生学习的方法 function study() { echo '我的名子叫:'.$this->name.' 我正在”.$this->school.” 学习
'; } } //定义一个子类“学生类“使用”extends”关键字来继承”人”类 class Student extends Person { var $school; //学生所在学校的属性 //这个学生学习的方法 function study() { echo '我的名子叫:'.$this->name.' 我正在”.$this->school.” 学习
'; } }
Through the definition of the "Student" class above, the Student class inherits all the member attributes and member methods of the Person class by using the "extends" keyword, and extends a member attribute "school" of the school where it is located, and a learning method "study()". Now the subclass "Student" and the objects created using instances of this class have the following attributes and methods:
The member attributes in the student class "Student" are:
Name: name;
Age: age;
Gender: sex;
School: school;
The member methods in the student class "Student" are:
Speaking method: say();
Learning method: study();
Through the use of the above class inheritance, the workload of creating objects and classes is simplified, and the reproducibility of the code is increased. However, from the above example, the impact of "reusability" and other inheritance is not particularly obvious. If you think about it more broadly, people have countless positions, such as students above, teachers, engineers, doctors, workers, etc., many, many more. If each class defines attributes and methods that are common to "people", think about it, there will be a lot of workload. These attributes and methods can be inherited from the "Person" human being.
12. Overload new methods
When learning PHP, you will find that methods in PHP cannot be overloaded. The so-called method overloading is to define the same method name and access our different methods with the same method name through different "number of parameters" or different "types of parameters". However, because PHP is a weakly typed language, it can receive different types of data in the method parameters itself, and because PHP methods can receive an indefinite number of parameters, it is not valid to call different methods with different method names by passing different numbers of parameters. So there is no method overloading in PHP. It cannot be overloaded, which means that methods with the same method name cannot be defined in your project. In addition, because PHP does not have the concept of name subspace, methods with the same name cannot be defined in the same page and included pages, nor methods with the same name as the methods provided by PHP. Of course, methods with the same name cannot be defined in the same class.
What do we mean by overloading new methods here? In fact, what we call overloading new methods is that the subclass overrides the existing method of the parent class, so why do we do this? Can’t the methods of the parent class be inherited and used directly? But there are some situations that we must cover. For example, in the example we mentioned earlier, the human "Person" has a "speak" method. All subclasses that inherit the "Person" class can "speak". Our "Student" class is a subclass of the "Person" class, so instances of "Student" can "speak". However, the "speak" method in the human being speaks the attributes in the "Person" class. The "Student" class extends the "Person" class and adds several new properties. If you use the inherited "say()" speaking method, you can only speak those properties inherited from the "Person" class. Then the newly extended properties cannot be spoken using the inherited "say()" method. Then some people asked, I define a new method in the "Student" subclass for speaking, wouldn't it be enough to speak all the properties in the subclass? Be sure not to do this. From an abstract point of view, a "student" cannot have two "speaking" methods. Even if you define two different speaking methods, which can achieve the functions you want, the inherited "speaking" method may not have a chance to be used, and you cannot delete the inherited one. At this time we will use coverage.
Although methods with the same name cannot be defined in PHP, in the two classes with a parent-child relationship, we can define methods with the same name as the parent class in the subclass, thus overriding the methods inherited from the parent class.
//定义一个“人”类做为父类 class Person { //下面是人的成员属性 var $name; //人的名子 var $sex; //人的性别 var $age; //人的年龄 //定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 function __construct($name, $sex, $age) { $this->name=$name; $this->sex=$sex; $this->age=$age; } //这个人可以说话的方法, 说出自己的属性 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } } class Student extends Person { var $school; //学生所在学校的属性 //这个学生学习的方法 function study() { echo '我的名子叫:'.$this->name.' 我正在”.$this->school.” 学习
'; } //这个学性可以说话的方法, 说出自己所有的属性,覆盖了父类的同名方法 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'我在'.$this->school.'上学.
'; } } ?> In the above example, we overwrote the "say()" method inherited from the parent class in the "Student" subclass. By overwriting, we achieved the extension of the "method".
However, although doing this solves the problem we mentioned above, in actual development, a method cannot be just one code or several codes. For example, the "say()" method in the "Person" class has 100 codes in it. If we want to overwrite this method and retain the original functions plus a little bit more, we must rewrite the original 100 codes. Coupled with a few extended codes, this is pretty good. However, 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 also have a solution, which is that the overridden method in the parent class can be called in the method of the subclass. That is, the original functions of the overridden method are taken over and some of its own functions are added. There are two ways to call the overridden method of the parent class in the method of the subclass:
One is to use the "class name::" of the parent class to call the overridden method in the parent class;
One is to use the "parent::" method to call the overridden method in the parent class;
class Student extends Person { var $school; //学生所在学校的属性 //这个学生学习的方法 function study() { echo '我的名子叫:'.$this->name.' 我正在”.$this->school.” 学习
'; } //这个学性可以说话的方法, 说出自己所有的属性,覆盖了父类的同名方法 function say() { //使用父类的“类名::“来调用父类中被覆盖的方法; // Person::say(); //或者使用“parent::”的方试来调用父类中被覆盖的方法; parent::say(); //加上一点自己的功能 echo “我的年龄是:'.$this->age.'我在'.$this->school.'上学.
'; } } Now you can access the overridden methods in the parent class in two ways. Which method should we choose best? Users may find that the code they write accesses the variables and functions of the parent class. This is especially true if the child class is very refined or the parent class is very specialized. Do not use the literal name of the parent class in the code. Instead, use the special name parent, which refers to the name of the parent class pointed to by the subclass in the extends declaration. Doing this avoids using the parent class's name in multiple places. If the inheritance tree needs to be modified during implementation, simply modify the extends declaration 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 constructor is redefined in the subclass, it will also override the constructor in the parent class. If you want to use a new constructor to assign values to all properties, you can use the same method.
class Student extends Person { var $school; //学生所在学校的属性 function __construct($name, $sex, $age, $school) { //使用父类中的方法为原有的属性赋值 parent::__construct($name, $sex, $age); $this->school=$school; } //这个学生学习的方法 function study() { echo '我的名子叫:'.$this->name.' 我正在”.$this->school.” 学习
'; } //这个人可以说话的方法, 说出自己的属性 function say() { parent::say(); //加上一点自己的功能 echo “我的年龄是:'.$this->age.'我在'.$this->school.'上学.
'; } }
13.Access type
Type access modifiers allow developers to restrict access to class members. This is a new feature of PHP5, but it is a good feature of the OOP language. And most OOP languages already support this feature. PHP5 supports the following three access modifiers:
There are three types: public (public, default), private (private) and protected (protected).
public public modifier, members in the class will have no access restrictions, and all external members can access (read and write) this class member (including member properties and member methods). In all versions before PHP5, members of the class in PHP are public, and in PHP5, if the member of the class does not specify a member access modifier, it will be considered public.
Example: public $name;
public function say(){};
private private modifier, a member defined as private is visible to all members in the same class, that is, there is no access restriction; but external code of the class is not allowed to change or even read operations, and subclasses of the class cannot access private-modified members.
Example: private $var1 = ‘A’; //properties
private function getValue(){} //function protected member modifier, members modified as protected cannot be accessed by external code of the class. However, subclasses of this class have access rights and can read and write properties and methods. External code of this subclass, including its subclasses, do not have permission to access its properties and methods.
Example: protected $name;
protected function say(){};
| private | protected | public | |
| in the same class | √ | √ | √ |
| in subclasses of class | √ | √ | |
| all external members | √ |
public; echo $this->protected; echo $this->private; } } $obj = new MyClass(); echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private /** * Define MyClass2 */ class MyClass2 extends MyClass { // We can redeclare the public and protected method, but not private protected $protected = 'Protected2'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } $obj2 = new MyClass2(); echo $obj->public; // Works echo $obj2->private; // Undefined echo $obj2->protected; // Fatal Error $obj2->printHello(); // Shows Public, Protected2, not Private ?> MyPublic(); $this->MyProtected(); $this->MyPrivate(); } } $myclass = new MyClass; $myclass->MyPublic(); // Works $myclass->MyProtected(); // Fatal Error $myclass->MyPrivate(); // Fatal Error $myclass->Foo(); // Public, Protected and Private work /** * Define MyClass2 */ class MyClass2 extends MyClass { // This is public function Foo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); // Fatal Error } } $myclass2 = new MyClass2; $myclass2->MyPublic(); // Works $myclass2->Foo2(); // Public and Protected work, not Private ?> In addition, when a subclass overrides a method of a parent class, one thing to note is that the access permissions of methods in the subclass must not be lower than the access permissions of the overridden methods of the parent class, that is, they must be higher than or equal to the access permissions of the parent class methods.
For example, if the access permission of the parent class method is protected, then the permissions to be overridden in the subclass must be protected and public. If the parent class method is public, then the method to be overridden in the subclass can only be public. In short, the method in the subclass must always be higher than or equal to the access permissions of the overridden method in the parent class.
14.Application of final keyword
This keyword can only be used to define classes and methods. The final keyword cannot be used to define member attributes, because final means constant. We use the define() function to define constants in PHP, so final cannot be used to define member attributes.
Classes marked with the final key cannot be inherited;
final class Person { …… } class Student extends Person { } The following error will occur:
Fatal error: Class Student may not inherit from final class (Person)
Methods marked with the final key cannot be overridden by subclasses and are the final version;
class Person { final function say() { } } class Student extends Person { function say() { } } The following error will occur:
Fatal error: Cannot override final method Person::say()
15.Use of static and const keywords
The Static keyword describes the member attributes and member methods in the class as static; what are the benefits of static members? Earlier we declared the "Person" human being. In the "Person" class, if we add an attribute of "the country to which the person belongs", and use the "Person" class to instantiate hundreds or more instance objects, each object will have the attribute of "the country to which the person belongs". If the project is developed for the Chinese, then each object will have a country attribute of "China". Other attributes are different, such as If we make the "country" attribute a static member, so that there is only one country attribute in the memory, and hundreds or more objects share this attribute, the static member can restrict external access, because the static member belongs to the class and does not belong to any object instance. It is the space allocated when the class is loaded for the first time. Other classes cannot access it. It is only shared with instances of the class, which can protect the member of the class to a certain extent;
Let's analyze it from the perspective of memory. The memory is logically divided into four segments. The objects are placed in the "heap memory", the references of the objects are placed in the "stack memory", and the static members are placed in the "initialized static segment". They are placed when the class is loaded for the first time and can be shared by every object in the heap memory, as shown below;
Static variables of a class are very similar to global variables and can be shared by all instances of the class. The same is true for static methods of a class, similar to global functions.
class Person { //下面是人的静态成员属性 public static $myCountry='中国'; // var $name; //人的名子 //这是人的静态成员方法 public static function say() { echo '我是中国人
'; } } //Output static attributes echo Person::$myCountry; //Access static methods Person::say(); //Reassign static attributes Person::$myCountry='United States'; echo Person::$myCountry; ?> Because static members are created when the class is first loaded, you can access static members by using the class name without requiring an object outside the class. As mentioned above, static members are shared by each instance object of this class, so can we use objects to access static members in the class? From the picture above, we can see that static members do not exist inside every object, but every object can be shared, so if we use objects to access members, there will be no such attribute definition, and static members cannot be accessed using objects. In other object-oriented languages, such as Java, you can use objects to access static members. If you can use objects to access static members in PHP, we try not to use them, because the purpose of static members when we are doing projects is to use class names to access them.
Static methods in a class can only access the static attributes of the class. Static methods in the class cannot access non-static members of the class. The reason is very simple. If we want to access other members of this class in the method of this class, we need to use the $this reference, and the $this reference pointer represents the object that calls this method. We said that static methods are not called with objects, but are accessed using the class name, so There is no object at all, and there is no reference to $this. Without the reference to $this, non-static members in the class cannot be accessed. And because static members in the class can be accessed without objects, the static methods in the class can only access the static attributes of the class. Since $this does not exist, we use a special class "self" to access other static members in the static method; self is similar to $this, except that self represents the class in which this static method is located. Therefore, in a static method, you can use the "class name" of the class where the method is located, or you can use "self" to access other static members. If there are no special circumstances, we usually use the latter, that is, the "self:: member attribute" method.
class Person { //下面是人的静态成员属性 public static $myCountry='中国'; //这是人的静态成员方法, 通过self访问其它静态成员 public static function say() { echo '我是'.self::$myCountry.'
'; } } //Access static method Person::say(); ?> Can static members be accessed in non-static methods? Of course it is possible, but you cannot use "$this" for reference and must use the class name or "self:: member attribute form".
const is a keyword for defining constants. The "define()" function is used to define constants in PHP, but the "const" keyword is used to define constants in a class. It is similar to #define in C. If its value is changed in the program, an error will occur. The member properties modified with "const" are accessed in the same way as the members modified with "static". They also use the "class name" and the "self" keyword in the method. But you don't need to use the "$" symbol, and you can't use objects to access it.
showConstant(); // echo $class::constant; is not allowed?>
16.__toString() method
We have said before that the method of declaring a method name starting with "-" in the class (provided by PHP to us) is a method that is automatically called and executed under different circumstances at a certain time. The "__toString()" method is also automatically called when directly outputting an object reference. Earlier we said that the object reference is a pointer, for example: "$p=new Person()", $p is a reference, we cannot use echo to directly output $p, this will output"Catchable fatal error: Object of class Person could not be converted to string", if you define the "__toString()" method in the class, no error will be generated when directly outputting the object reference. Instead, the "__toString()" method will be automatically called to output the characters returned in the "__toString()" method, so the "__toString()" method must have a return value (return statement).
foo = $foo; } //Define a __toString method and return a member attribute $foo public function __toString() { return $this->foo; } } $class = new TestClass('Hello'); //Output the object directly echo $class; ?> The output of the above example: Hello
17.Clone objects
Sometimes we need to use two or more identical objects in a project. If you use the "new" keyword to re-create the object and then assign the same attributes, this is cumbersome and error-prone. Therefore, it is very necessary to completely clone an identical object based on an object. Moreover, after cloning, the two objects will not interfere with each other.
class Person { //下面是人的成员属性 var $name; //人的名子 var $sex; //人的性别 var $age; //人的年龄 //定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 function __construct($name='', $sex='', $age='') { $this->name=$name; $this->sex=$sex; $this->age=$age; } //这个人可以说话的方法, 说出自己的属性 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } } $p1=new Person('张三', '男', 20); //使用“clone”克隆新对象p2,和p1对象具有相同的属性和方法。 $p2=clone $p1; $p2->say(); ?> In PHP5 we use the "clone" keyword to clone objects;
PHP5 defines a special method name "__clone()", which is a method that is automatically called when an object is cloned. Using the "__clone()" method will create an object with the same properties and methods as the original object. If you want to change the content of the original object after cloning, you need to rewrite the original properties and methods in __clone(). The "__clone()" method can have no parameters. It automatically contains two pointers, $this and $that, $this points to the copy, and $that points to the original;
class Person { //下面是人的成员属性 var $name; //人的名子 var $sex; //人的性别 var $age; //人的年龄 //定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 function __construct($name='', $sex='', $age='') { $this->name=$name; $this->sex=$sex; $this->age=$age; } //这个人可以说话的方法, 说出自己的属性 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } //对象克隆时自动调用的方法, 如果想在克隆后改变原对象的内容,需要在__clone()中重写原本的属性和方法 function __clone() { //$this指的复本p2, 而$that是指向原本p1,这样就在本方法里,改变了复本的属性。 $this->name='我是假的$that->name'; $this->age=30; } } $p1=new Person('张三', '男', 20); $p2=clone $p1; $p1->say(); $p2->say(); ?> The above example output:
My name is: Zhang San Gender: Male My age is: 20
My name is: I am the fake Zhang San Gender: Male My age is: 30
18.__call handles calling errors
In program development, if when using an object to call an internal method of the object, the called method does not exist, then the program will error, and then the program will exit and cannot continue to execute. So when the program calls a method that does not exist inside the object, can we be prompted that the method called and the parameters used do not exist, but the program can continue to execute. At this time, we have to use the method "__call()" that is automatically called when calling a method that does not exist.
demo('one', 'two', 'three'); //程序不会执行到这里 echo 'this is a test
'; ?>
The following error occurs in the above example, and the program cannot continue to execute;
Fatal error: Call to undefined method Test::demo()
Next, we add the "__call()" method. This method has two parameters. The first parameter is the process of calling a non-existent method. When the __call() method is automatically called, the method name of the non-existent method is passed to the first parameter. The second parameter is to pass in the multiple parameters of this method in the form of an array.
/n'; } } //产生一个Test类的对象 $test=new Test(); //调用对象里不存在的方法 $test->demo('one', 'two', 'three'); //程序不会退出可以执行到这里 echo 'this is a test
'; ?> The output of the above example is:
The function you called: demo (parameter: Array ( [0] => one [1] => two [2] => three ) ) does not exist!
this is a test.
19. Abstract methods and abstract classes
In OOP language, a class can have one or more subclasses, and each class has at least one public method as an interface for external code to access it. Abstract methods are introduced to facilitate inheritance. Let's first take a look at the definitions of abstract classes and abstract methods before explaining their uses.
What is an abstract method? The method we define in the class without a method body is an abstract method. The so-called no method body means that when the method is declared, there are no curly braces and its contents, but a semicolon is added directly after the method name when declaring it. In addition, when declaring an abstract method, a keyword "abstract" must be added to modify it;
For example:
abstract function fun1();
abstract function fun2();
The above example is the abstract methods "fun1()" and "fun2()" without a method body modified by "abstract". Don't 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, then the class must be defined as an abstract class, and the abstract class must also be modified with the "abstract" keyword; an abstract class can have methods and member attributes that are not abstract, but as long as one method is an abstract method, the class must be declared as an abstract class and modified with "abstract".
For example:
abstract class Demo { var $test; abstract function fun1(); abstract function fun2(); function fun3() { …. } }
In the above example, an abstract class "Demo" is defined and modified with "abstract". In this class, a member attribute "$test" is defined, two abstract methods "fun1" and "fun2" and a non-abstract method fun3(); so how do we use abstract classes? The most important point is that abstract classes cannot produce instance objects, so they cannot be used directly. We have mentioned many times before that classes cannot be used directly. We are using objects instantiated through classes. So if abstract classes cannot produce instance objects, what is the use of declaring abstract classes? We use abstract methods as templates for subclass overloading. Defining an abstract class is equivalent to defining a specification, which requires subclasses to comply. After the subclass succeeds the abstract class, it implements the abstract methods in the abstract class according to the needs of the subclass. The subclass must implement all the abstract methods in the parent class. Otherwise, if there are still abstract methods in the subclass, then the subclass is still an abstract class and cannot be instantiated. Why do we have to inherit from the abstract class? Because sometimes if we want to implement some functions, we must inherit from an abstract class, otherwise you will not be able to implement these functions. If you inherit an abstract class, you must implement the abstract methods in the class;
abstract class Demo { var $test; abstract function fun1(); abstract function fun2(); function fun3() { …. } } $demo=new Demo(); //抽象类为能产生实例对象,所以这样做是错的,实例化对象交给子类 class Test extends Demo { function fun1() { … } function fun2() { … } } $test=new Test(); //子类可以实例化对象,因为实现了父类中所有抽象方法 ?>
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. In order to solve this problem, PHP introduced interfaces. The idea of the interface is to specify a series of methods that a class that implements the interface must implement. The interface is a special abstract class, and the abstract class is a special class, so the interface is also a special class. Why is the interface a special abstract class? If all methods in an abstract class are abstract methods, then we use "interface" as a declaration method; that is to say, all methods in the interface must be declared as abstract methods, and variables cannot be declared in the interface, and all members in the interface have public permissions. Therefore, subclasses must also use public permissions when implementing them.
When declaring a class, we use the keyword "class", and the interface, a special class, uses the keyword "interface";
Class definition: class class name {…}, interface declaration: interface interface name {…}
In the above example, an interface "one" is defined, which declares two abstract methods "fun1" and "fun2". Because all methods in the interface are abstract methods, there is no need to use the "abstract" keyword when declaring abstract methods like an abstract class. This keyword is already added by default. In addition, in The "public" access permission in the interface can also be removed, because the default is public, because all members in the interface must be public, so we cannot use "private" and "protected" permissions for members in the interface, and must use public or default. In addition, we also declared a constant "constant" in the interface. Because variable members cannot be used in the interface, we have to use the const keyword declaration.
Because the interface is a special abstract class, all methods in it are abstract methods, so the interface cannot produce instance objects; it also serves as a specification, and all abstract methods need to be implemented by subclasses.
We can use the "extends" keyword to let one interface inherit another interface;
When we define a subclass of an interface to implement all abstract methods in the interface, the keyword used is "implements" instead of "extends" as we mentioned before;
We can also use abstract classes to implement some abstract methods in the interface, but in order to instantiate an object, this abstract class must have a subclass to implement all its abstract methods;
As we said before, PHP has single inheritance. A class can only have one parent class, but a class can implement multiple interfaces, which is equivalent to a class having to comply with multiple specifications, just like we must not only abide by the laws of the country, but also abide by the school rules if we are in school;
In PHP, not only can a class implement multiple interfaces, but you can also implement multiple interfaces while inheriting a class. You must first inherit the class and then implement the interface;
21. Polymorphic applications
Polymorphism is one of the three major characteristics of object-oriented objects besides encapsulation and inheritance. In my personal opinion, although polymorphism can be achieved in PHP, compared with object-oriented languages such as C++ and Java, polymorphism is not so prominent because PHP itself is a weakly typed language. There is no conversion of parent class objects into subclass objects or subclass objects into parent classes. The problem of class objects, so the application of polymorphism is not so obvious; the so-called polymorphism refers to the ability of a program to handle multiple types of objects. For example, when working in a company, the financial department pays wages every month. The same salary payment method, different employees or employees in different positions in the company are all paid through this method, but the wages are all different. Therefore, the same method of paying wages appears in many forms. For object-oriented programs, polymorphism is to assign the subclass object to the parent class reference, and then call the parent class method to execute the method of the subclass overriding the parent class. However, in PHP, it is weakly typed, and the object references are the same regardless of parent class reference or subclass reference.
Let's look at an example now. First of all, to use polymorphism, there must be a relationship between parent class objects and subclass objects. Make a shape interface or abstract class as the parent class. There are two abstract methods in it, one to find the perimeter, and the other to find the area. The subclasses of this interface have many different shapes, and each shape has a perimeter and an area. And because the parent class is an interface, the subclass must implement the two abstract methods of perimeter and area of the parent class. The purpose of this is that each subclass of different shapes must comply with the specifications of the parent class interface and have methods for calculating perimeter and area.
//定义了一个形状的接口,里面有两个抽象方法让子类去实现 interface Shape { function area(); function perimeter(); } //定义了一个矩形子类实现了形状接口中的周长和面积 class Rect implements Shape { private $width; private $height; function __construct($width, $height) { $this->width=$width; $this->height=$height; } function area() { return '矩形的面积是:'.($this->width*$this->height); } function perimeter() { return '矩形的周长是:'.(2*($this->width+$this->height)); } } //定义了一个圆形子类实现了形状接口中的周长和面积 class Circular implements Shape { private $radius; function __construct($radius) { $this->radius=$radius; } function area() { return '圆形的面积是:'.(3.14*$this->radius*$this->radius); } function perimeter() { return '圆形的周长是:'.(2*3.14*$this->radius); } } //把子类矩形对象赋给形状的一个引用 $shape=new Rect(5, 10); echo $shape->area().'
'; echo $shape->perimeter().'
'; //把子类圆形对象赋给形状的一个引用 $shape=new Circular(10); echo $shape->area().'
'; echo $shape->perimeter().'
'; ?> The execution result of the above example:
The area of the rectangle is: 50
The perimeter of the rectangle is: 30
The area of the circle is: 314
The circumference of a circle is: 62.8
From the above example, we can see that when the rectangular object and the circular object are assigned to the variable $shape respectively, and the area and perimeter methods in the $shape reference are called, different results appear. This is a polymorphic application. In fact, in our weakly typed object-oriented language like PHP, the polymorphic feature is not particularly obvious. In fact, it is the variable application of object type variables.
22. Serialize objects
有时候需要把一个对象在网络上传输,为了方便传输,可以把整个对象转化为二进制串,等到达另一端时,再还原为原来的对象,这个过程称之为串行化, 就像我们现在想把一辆汽车通过轮船运到美国去,因为汽车的体积比较大,我们可以把汽车拆开成小的部件,然后我们把这些部件通过轮般运到美国去,到了美国再把这些部件组装回汽车。
There are two situations where we must serialize objects. The first situation is to serialize an object when transmitting it over the network. The second situation is to use serialization when writing an object to a file or database.
There are two processes in serialization. One is serialization, which is to convert an object into a binary string. We use the serialize() function to serialize an object. The other is deserialization, which is to convert the object into a binary string and then convert it into an object. We use the unserialize() function to deserialize an object.
PHP中serialize()函数的参数为对象名,返回值为一个字符串,Serialize()返回的字符串含义模糊,一般我们不会解析这个串来得到对象的信息,我们只要把返回来的这个字符串传到网络另一端或是保存到方件中即可。
PHPunserialize()function to deserialize the object. The parameter of this function is the return value of the serialize() function. The output is of course the reorganized object.
class Person { //下面是人的成员属性 var $name; //人的名子 var $sex; //人的性别 var $age; //人的年龄 //定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 function __construct($name='', $sex='', $age='') { $this->name=$name; $this->sex=$sex; $this->age=$age; } //这个人可以说话的方法, 说出自己的属性 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } } $p1=new Person('张三', '男', 20); $p1_string=serialize($p1); //把一个对象串行化,返一个字符串 echo $p1_string.'
'; //串行化的字符串我们通常不去解析 $p2=unserialize($p1_string); //把一个串行化的字符串反串行化形成对象$p2 $p2->say(); ?> The output of the above example is:
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: Zhang San Gender: Male My age is: 20
在php5中有两个魔术方法__sleep()方法和__wakeup()方法,在对象串行化的时候,会调用一个__sleep()方法来完成一些睡前的事情;而在重新醒来,即由二进制串重新组成一个对象的时候,则会自动调用PHP的另一个函数__wakeup(),做一些对象醒来就要做的动作。
The __sleep() function does not accept any parameters, but returns an array containing the attributes that need to be serialized. Attributes that are not included will be ignored during serialization. If there is no __sleep() method, PHP will save all attributes.
class Person { //下面是人的成员属性 var $name; //人的名子 var $sex; //人的性别 var $age; //人的年龄 //定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 function __construct($name='', $sex='', $age='') { $this->name=$name; $this->sex=$sex; $this->age=$age; } //这个人可以说话的方法, 说出自己的属性 function say() { echo '我的名子叫:'.$this->name.' 性别:'.$this->sex.' 我的年龄是:'.$this->age.'
'; } //指定串行化时把返回的数组中$name和$age值串行化,忽略没在数组中的属性$sex function __sleep() { $arr=array('name', 'age'); return($arr); } //重新生成对象时,并重新赋值$age为40 function __wakeup() { $this->age = 40; } } $p1=new Person('张三', '男', 20); //把一个对象串行化,返一个字符串,调用了__sleep()方法,忽略没在数组中的属性$sex $p1_string=serialize($p1); echo $p1_string.'
'; //串行化的字符串我们通常不去解析 $p2=unserialize($p1_string); //反串行化形成对象$p2重新赋值$age为40 $p2->say(); ?> The output value of the above 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 classes
When many developers write object-oriented applications, they create a PHP source file for each class definition. A big annoyance is having to write a long list of include files at the beginning of each script (one file per class).
在软件开发的系统中,不可能把所有的类都写在一个PHP文件中,当在一个PHP文件中需要调用另一个文件中声明的类时,就需要通过include把这个文件引入。不过有的时候,在文件众多的项目中,要一一将所需类的文件都include进来,是一个很让人头疼的事,所以我们能不能在用到什么类的时候,再把这个类所在的php文件导入呢?这就是我们这里我们要讲的自动加载类。
在 PHP 5 中,可以定义一个 __autoload()函数,它会在试图使用尚未被定义的类时自动调用,通过调用此函数,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类, __autoload()函数接收的一个参数,就是你想加载的类的类名,所以你做项目时,在组织定义类的文件名时,需要按照一定的规则,最好以类名为中心,也可以加上统一的前缀或后缀形成文件名,比如xxx_classname.php、classname_xxx.php以及就是classname.php等等.
This example attempts to load the MyClass1 and MyClass2 classes from the MyClass1.php and MyClass2.php files respectively
This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)". Please keep the following tags for sharing and interpretation:
Original author:Jake Tao,source:"PHP object-oriented technology (detailed explanation, suitable for entry)"