Php basics (5) --- PHP object-oriented, --- php object-oriented

Source: Internet
Author: User
Tags autoload object serialization php basics

Php basics (5) --- PHP object-oriented, --- php object-oriented

Preface: 

Today, I will introduce PHP's object-oriented features. Speaking of object-oriented, I have to mention process-oriented because I often cannot tell clearly at the beginning. So what is the difference between object-oriented and process-oriented? The following is a brief introduction:

Object-orientedFocus on which object to handle a problem.

The biggest feature is that an object is obtained from the class by a class with properties and functions to solve the problem.

Process-orientedFocus on solving a problem. Its biggest feature is a series of processes by which one function solves this problem.

 

After learning about the differences between object-oriented and process-oriented, let's take a look at the basic knowledge about PHP object-oriented.

* ** Keywords in this chapter: Object-oriented basics, encapsulation and inheritance, PHP keywords, Singleton, Object serialization and magic methods, abstract classes and abstract methods, interfaces and polymorphism.

 

 

 

 

What you need to know ~~~ We need to know that PHP Object-oriented has three main characteristics: inheritance, encapsulation, and polymorphism.

 

I. Object-oriented Basics

 

I Object-oriented

1. What is a class?
A collection of individuals with the same attributes (features) and methods (Actions). A class is an abstract concept.

2. What is an object?
An individual with specific attribute values obtained from a class is called an object. An object is a specific individual.
Eg: Human; James

3. What is the relationship between classes and objects?
Class is the abstraction of objects! Objects are class-specific!
Classes only indicate the attributes of such objects, but do not have specific values. Therefore, classes are abstract.
Objects assign values to all attributes of a class to produce specific individuals. All objects are specific.

 

II Class declaration and instantiation

1. How to declare a class:

Class name {
Access modifier $ attribute [= default value];
[Access modifier] function Method (){}
}

2. Considerations for declaring a class:
① A class name can only contain letters, numbers, and underscores. It cannot start with a number and must comply with the rules of the big hump;
② Class names must be modified using class, and class names must not be followed ();
③ The attribute must contain an access modifier. The method can be without an access modifier.

3. Call of instantiated objects and Object Property methods:
$ Object name = new Class Name (); // () can be left blank

Class external call attributes and methods:
$ Object Name-> $ attribute name; // use-> when calling an attribute, the attribute name cannot contain the $ symbol.

Class Internal call attributes and methods:
$ This-> $ attribute name;

 

3. Constructor

1. What is a constructor?
Constructor is a special function in the class. When we use the new keyword to instantiate an object, it is equivalent to calling the constructor of the class.

2. What is the role of Constructors?
It is called automatically when an object is instantiated to assign initial values to the object's attributes!

3. constructor Syntax:
① Name of the constructor, which must have the same name as the class
[Public] function Person ($ name ){
$ This-> name = $ name;
}
② Use magic _ construct
[Public] function _ construct ($ name ){
$ This-> name = $ name;
}
4. constructor considerations:
① In the first writing method, the constructor name must be the same as the class name !!!!
② If a class does not have a handwritten constructor, the system will have an empty parameter structure by default, so you can use new Person ();
If we write a constructor with parameters, there will be no free parameter construction, that is, new Person () cannot be used directly ();
The parameter list in () after Person must meet the requirements of the constructor !!!!
③ If both constructors exist at the same time, _ construct will be used.

5. destructor :__ destruct ():
① The Destructor is automatically called before the object is destroyed and released;
② The Destructor cannot contain any parameters;
③ Destructor are often used to release resources and close resources after an object is used.

6. Magic methods:
In PHP, we provide a series of functions starting with _, which do not need to be manually called by ourselves,
It is automatically called at the right time. Such functions are called magic functions.
Eg: function _ construct () {} is automatically called when the class is new to an object.
Function _ destruct () {} is automatically called when the object is destroyed.


In addition to magic methods, we require that user-defined functions and methods cannot start.

Finally, for classes with complex functions, we write them to a class file separately.

Class file name, in the same lower case, using the "class Name lower case. class. php" method.
When using this class in other files, you can use include to import this ". class. php" file.

 

 

Ii. encapsulation and inheritance

 

1. What is encapsulation?
The access modifier is used to privatize the attributes and methods that do not require external access in the class to implement access control.

* Note: access control is implemented instead of Access denied. That is to say, after we privatize the attributes, we need to provide corresponding methods for users to process the attributes through the methods we provide.

2. What is the role of encapsulation?
① The user only cares about the functions provided by the class, and does not care about the implementation details of the functions! (Encapsulation method)
② Control user data to prevent illegal data setting and control the data returned to the user (attribute encapsulation + set/get method)

3. How to Implement encapsulation?
① Encapsulation of methods
For some methods that are only used inside the class, instead of providing external services, we can use private for private processing.

1 private function formatName () {}// this method can only use $ this within the class to call 2 function showName () {3 $ this-> formatName (); 4}

② Encapsulation of attributes + set/get Method
To control the setting and reading of attributes, You Can privatize the attributes and require users to set them using the set/get method we provide.

1 private $ age; 2 // set method 3 function setAge ($ age) {4 $ this-> age = $ age; 5} 6 // get Method 7 function getAge () {8 return $ this-> age; 9}

$ Object-> getAge ();
$ Object-> setAge (12 );

③ Encapsulation of attributes + magic methods

1 private $age;2 function __get($key){3 return $this->$key;4 }
5 function __set($key,$value){6 $this->$key=$value;7 }

$ Object-> age; // when accessing the private property of an object, the _ get () magic method is automatically called and the accessed property name is passed to the _ get () method;
$ Object-> age = 12; // when setting the private property of an object, the _ set () magic method is automatically called, and the set property name and attribute value are passed to _ set () method;

Note: In the magic method, you can use the branch structure to determine the difference between the $ key and perform different operations.

4. encapsulation magic methods:
① _ Set ($ key, $ value): this parameter is automatically called when a class private attribute is assigned. Two parameters are passed to the method during the call: the attribute name and attribute value to be set.
② _ Get ($ key, $ value): it is automatically called when reading private attributes of the class. A parameter is passed to the method during the call and the attribute name to be read;
③ _ Isset ($ key): it is automatically called when the isset () function is used externally to detect private attributes.
>>> Isset () is used outside the class. Private attributes are detected and cannot be detected by default. False
>>> Therefore, we can use the _ isset () function to return internal detection results during automatic calling.

1 function __isset($key){2 return isset($this -> $key);3 }

When isset ($ Object Name-> private attribute) is used externally, the result returned by _ isset () is automatically called!

④ _ Unset ($ key): it is automatically called when the unset () function is used externally to delete private attributes;
1 function _ unset ($ key) {2 unset ($ this-> $ key); 3}
When the external uses unset ($ Object Name-> private attribute); When deleting an attribute, the attribute name is automatically passed to _ unset () and handled by this magic method.


[Basic inherited knowledge]
1. How to Implement inheritance?
Use the extends keyword for the subclass to inherit the parent class;
Class Student extends Person {}

2. What are precautions for inheritance?
① Subclass can only inherit non-private attributes of the parent class.
② After the subclass inherits the parent class, it is equivalent to copying the attributes and methods of the parent class to the subclass and can be called directly using $ this.
③ PHP can only inherit from one class, but cannot inherit from multiple classes. However, a class is inherited at multiple layers.
Class Person {}
Class Adult extends Person {}
Class Student extends Adult {}
// The Student class has both the attributes and methods of the Adult class and the Person class.

3. Method override)
Condition 1: subclass inherits the parent class
Condition 2: The subclass overrides existing methods of the parent class.

The method overwrites the preceding two conditions. After overwriting, The subclass calls the method and calls its own method.
In addition to method override, subclass can also have attributes with the same name as the parent class to overwrite the attributes.

If the subclass overrides the parent class method, how does one call the method with the same name as the parent class in the subclass?

Partent: Method Name ();
Therefore, when the subclass inherits the parent class, the first step in the subclass construction is to call the parent class construction for copying.

1 function __construct($name,$sex,$school){2 partent::__construct($name,$sex);3 $this -> school = $school;4 }

 

Iii. PHP keywords

 

1. final
① Final modifier class. This class is the final class and cannot be inherited!
② Final modifier. This method is the final method and cannot be overwritten!
③ Final cannot modify attributes.

2. static
① Attributes and methods can be modified. They are called static attributes and static methods, also called class attributes and class methods;
② Static attributes and static methods can only be called directly using class names.
Use "Class Name: $ static property", "Class Name: static method ()"
Person: $ sex; Person: say ();
③ Static attributes and methods are declared during class loading and generated prior to the object.
④ Non-static attributes or methods cannot be called in static methods;
A non-static method can call static attributes and methods.
(Because static attributes and methods have been generated during class loading, rather than static attribute methods, they are not instantiated yet)
⑤ In the class, you can use the self keyword to represent the class name.

1 class Person{2 static $sex = "nan";3 function say(){4 echo self::$sex;5 }6 }

⑥ Static attributes are shared, that is, many new objects are generated and shared.

3. const keywords:
Declare a constant in the class. It cannot be a define () function! You must use the const keyword.
Similar to the define () Declaration, the const keyword declaration constant cannot contain $, and must all be capitalized!
Once declared, the constant cannot be changed. The call is the same as static, and the class name is used to call the Person: constant.

4. instanceof OPERATOR:
Checks whether an object is an instance of a class. (Including elders, grandfathers, grandfathers ......)

$zhangsan instanceof Person;

 

[Summary] several special Operators
1. Only strings can be connected ;"".""
2. => when declaring an array, the associated key and value ["key" => "value"]
3.-> an object (an object generated by $ this new) calls Member attributes and member methods;
4.: ① use the parent keyword to call the method with the same name in the parent class: parent: say ();
② Use the class name (and self) to call static attributes, static methods, and constants in the class.

 

Iv. Singleton

 

The Singleton mode is also called the singleton mode. It can be guaranteed that only one object instance can exist in a class.

Implementation points:
① The constructor is private and cannot use the new keyword to create an object.
② Provide external methods for obtaining objects, and determine whether the object is empty in the method.
If it is null, the object is created and returned. If it is not null, the object is returned directly.
③ The attributes of the Instance Object and the method for obtaining the object must be static.
④ Then, the object can only be created using the static method we provide.
Eg: $ s1 = Singleton: getSingle ();

 

V. Object serialization and magic methods

 

* ** Keywords: clone and _ clone, _ antoload (), serialization and deserialization (serialization and deserialization) summary of type constraints and magic methods (12)

 

I Clone and _ clone


1. When I use = to talk about an object and assign a value to another object, the address of the object is actually assigned.
Two objects point to the same address, so one object changes, and the other changes.
Eg: $ lisi = $ zhangsan;
2. If you want to completely clone an object from another object, the two objects are independent and do not interfere with each other,
Use the clone keyword;
Eg: $ lisi = clone $ zhangsan; // two objects do not interfere with each other
3. _ clone ():
① When the clone keyword is used to clone an object, the clone function is automatically called.
② _ Clone () is similar to the constructor used during cloning. You can assign an initial value to the new cloned object.
③ $ This in the _ clone () function indicates the newly cloned object.
In some versions, you can use $ that to represent the cloned object, which is not supported by most versions.
4. _ toString ()
Echo $ zhangsan is called when echo and other output statements are used to print objects directly;
You can specify the string returned by the _ toString () function;

1 function _ toString () {2 return "haha"; 3} 4 echo $ zhangsan; // The result is: haha

5. _ call ()
When an undefined or undisclosed method is called in a class, the _ call () method is automatically executed.
During Automatic Execution, two parameters are passed to the _ call () method;
Parameter 1: name of the called Method
Parameter 2: (array) list of parameters for calling methods.

 

2__ antoload ()


① This is the only magic method not used in the class;
② This magic method is automatically called when a nonexistent class is instantiated;
③ During the call, a parameter is automatically passed to _ autoload (): the instantiated class name.
Therefore, you can use this method to automatically load files.

1 function _ autoload ($ className) {2 include "class /". strtolower ($ className ). ". class. php "; 3} 4 $ zhangsan = new Person (); // if there is no Person class in this file, _ autoload () is automatically executed to load person. class. PHP File

 

3. Object-oriented serialization and deserialization (serialization and deserialization)


1. serialization: the process of converting an object into a string through a series of operations, called serialization.

(An object records itself by writing a value that describes its status)

2. deserialization: the process of converting serialized strings into objects is called deserialization;
3. When will serialization be used?
① When the object needs to be transmitted over the network
② When objects need to be permanently stored in files or databases
4. How to achieve serialization and deserialization
Serializable: $ str = serialize ($ zhangsan );
Deserialization: $ duixiang = unserialize ($ str );
5. _ sleep () magic method:
① When the object is serialized, the _ sleep () function is automatically executed;
The _ sleep () function requires that an array be returned. The values in the array are serializable attributes. Attributes not in the array cannot be serialized;
Function _ sleep (){
Return array ("name", "age"); // only two attributes of name/age can be serialized.
}

6. _ wakeup () magic Method
① When the object is deserialized, the _ wakeup () method is automatically called;
② When automatic calling is performed, it is used to re-assign values to the new object attributes generated by the deserialization.
1 function _ wakeup () {2 $ this-> name = "Li Si"; 3}

Thu Type Constraints


1. Type constraints: When a variable is added with a data type, this variable can only store the corresponding data type.
(This operation is common in strong-type languages. In PHP, only the type constraints of arrays and objects can be implemented)
2. If the type constraint is a class, you can use both the class and its subclass objects.
3. In PHP, type constraints can only occur in function parameters.

1 class Person {} 2 class Student extends Person {} 3 function func (Person $ p) {// form parameter of the constrained function, accept only the Person class and the Person subclass 4 echo "1111"; 5 echo $ p-> name; 6}

Func (new Person (); √
Func (new Student (); √
Func ("111"); ×

Like new Person ();, we call it an "anonymous object ";

※※※Base class: parent class
※※※Derived class: subclass

V. Summary of magic methods


1. _ construct (): constructor. It is automatically called when an object is new.
2. _ destruct (): destructor, which is called automatically before an object is destroyed.
3. _ get (): it is automatically called when the private attribute in the condition class is used. Pass the read attribute name and return $ this-> attribute name
4. _ set (): it is automatically called when values are assigned to private attributes of a class. Pass the attribute name and attribute value to be set;
5. _ isset (): it is automatically called when isset () is used to detect the private attributes of an object. Pass the detected attribute name and return isset ($ this-> attribute name );
6. _ unset (): it is automatically called when unset () is used to delete the private attributes of an object. The name of the deleted attribute is passed, and the unset ($ this-> attribute name) is executed in the method );
7. _ toString (): it is automatically called when echo is used to print an object. Returns the content that you want to display when printing an object. The returned content must be a string;
8. _ call (): automatically calls an undefined or undisclosed method in a class. Pass the called function name and parameter list array;
9. _ clone (): it is automatically called when an object is cloned using the clone keyword. The function is to initialize and assign values to the new cloned object;
10. _ sleep (): automatically called when the object is serialized. Returns an array. The values in the array are serializable attributes;
11. _ wakeup (): automatically called when the object is deserialized. Initialize and assign values to the newly generated objects for deserialization;
12. _ autoload (): The function must be declared outside the class. It is automatically called when an undeclared class is instantiated. The passed instantiated class name can be used to automatically load the corresponding class file.

 

6. abstract classes and abstract methods

 

1. What is an abstract method?
The method body {} does not exist. You must use the abstract keyword to modify the method body. This method is called an abstract method.
Abstract function say (); // abstract Method

2. What is an abstract class?
Classes modified with abstract keywords are abstract classes.
Abstract class Person {}

3. Notes for abstract classes:
① Abstract classes can contain non-abstract methods;
② Classes that contain abstract methods must be abstract classes. abstract classes do not necessarily contain abstract methods;
③ Abstract class, which cannot be instantiated. (Abstract classes may contain abstract methods. abstract methods do not have method bodies, and instantiation calls do not make sense)
The purpose of using abstract classes is to restrict instantiation !!!

4. If the subclass inherits the abstract class, the subclass must override all abstract methods of the parent class, unless the subclass is also an abstract class.

5. What is the role of an abstract class?
① Restrict instantiation. (An abstract class is an incomplete class. The abstract method in it does not have a method body, so it cannot be instantiated)
② Abstract classes provide a standard for subclass inheritance. If a subclass inherits an abstract class, it must contain and implement the defined abstract methods in the abstract class.

 

VII. interfaces and Polymorphism

 

I Interface


1. What is an interface?
An interface is a specification that provides a set of methods that must be implemented by the classes that implement the interface.
The interface uses the interface keyword Declaration;
Interface Inter {}

2. All methods in the interface must be abstract methods.
Abstract modification is not required or applicable to abstract methods in interfaces.

3. Variables and attributes cannot be declared in the interface. Only constants can be used !!!

4. The interface can inherit the interface and use the extends keyword!
You can use the extends inheritance interface to implement multi-inheritance.
Interface int1 extends Inter, Inter2 {}

5. classes can implement interfaces and use the implements keyword!
Class implements interfaces using implements. Multiple Interfaces can be implemented at the same time. Multiple Interfaces are separated by commas;
Abstract class Person implements Inter, Inter2 {}
If a class implements one or more interfaces, this class must implement all abstract methods in all interfaces!
Unless, this class is an abstract class.

※[ Interface & abstract class differences]
1. In the declaration method, the interface uses the interface keyword, and the abstract class is used for the abstract class.
2. In implementation/inheritance mode, a class uses extends to inherit the abstract class and implements to implement the interface.
3. abstract classes can only be inherited by a single user, and multiple interfaces can be implemented. (Interface extends Interface), multiple implementations (class implements Interface)
4. abstract classes can contain non-Abstract METHODS. interfaces can only contain abstract methods, but not abstract methods.
Abstract METHODS in abstract classes must be modified using abstract keywords. abstract METHODS In interfaces cannot contain modifiers.
5. An abstract class is a class that can have attributes and variables. An interface can only contain constants.

II Polymorphism

2. Polymorphism
1. A class is inherited by multiple subclasses.
If a method of this class shows different functions in multiple subclasses, we call this behavior a polymorphism.

2. Necessary ways to achieve polymorphism:
① Subclass inherits the parent class;
② Subclasses override the parent class method;
③ Parent class references to subclass objects

 

Today's content will be shared here first ~ Learn together and make progress together !!!!

 

 

 


 

 

 

Author: XI Zhao hope
Source: http://www.cnblogs.com/hope666/

 

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.