Detailed explanation of my understanding of object-oriented in PHP

零下一度
Release: 2023-03-12 12:22:01
Original
1469 people have browsed it

Foreword:

Today I will introduce to you the object-oriented nature of PHP. Speaking of object-oriented, I have to mention process-oriented, because when I was a beginner, I often couldn't tell the difference. So what is the difference between object-oriented and process-oriented? Let me give you a brief introduction:

Object-orientedFocus on which object handles a problem.

Its biggest feature is that it consists of classes with attributes and functions, and objects can be obtained from the classes to solve problems.

Process-orientedFocus on the process of solving a problem. The biggest feature is that a series of processes are used to solve this problem one by one.

After understanding the difference between object-oriented and process-oriented, let’s learn the basic knowledge of object-oriented PHP.

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

What you need to know~~~The PHP object-oriented features we need to know have three major characteristics: inheritance; encapsulation; polymorphism.

1. Object-oriented basics

Object-oriented

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

2. What is an object?
The individual with specific attribute values ​​obtained from the class is called an object. The object is a specific individual.
eg: Human; Zhang San

3. What is the relationship between classes and objects?
A class is an abstraction of an object! Objects are the reification of classes!
The class only indicates what attributes this type of object has, but cannot have specific values, so the class is abstract.
The object is a specific individual generated after assigning all attributes of the class. All objects are specific.

2. Class declaration and instantiation
1. How to declare a class:
class class name{
Access modifier $property[=default value];
[Access modifier] function method(){}
}

2. Notes on declaring a class:
① The class name can only be composed of alphanumeric and underscores, and cannot start with a number. It must comply with the big camel case rule ;
②The class name must be modified with class, and there must not be () after the class name;
③The attribute must have access modifier, and the method can not have access modifier.

3. Calling instantiated objects and object attribute methods:
$Object name = new class name (); //() can be omitted

Call properties and methods from outside the class:
$Object name-> $Attribute name; //When using -> to call an attribute, the attribute name The $ symbol cannot be used

Calling properties and methods within the class:
$this -> $property name;

3. Constructor
1. What is a constructor?
The 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 function of the constructor?
When instantiating an object, it is automatically called and used to assign initial values ​​to the properties of the object!

3. How to write the constructor:
①The name of the constructor must be the same as the class name
[public] function Person($name){
$this -> name = $name;
}
②Use the magic method __construct
[public] function __construct($name){
$this -> name = $name;
}
4. Notes on constructors:
①The first way of writing, the name of the constructor must be the same as the class! ! ! !
②If a class does not have a handwritten constructor, the system will have an empty parameter constructor by default, so you can use new Person();
If we write a constructor with Parameter constructor, there will no longer be an empty parameter constructor, that is, new Person() cannot be used directly;
The parameter list in () after
Person must meet the requirements of the constructor ! ! ! !

③If two 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 take any parameters;

③The destructor is often used to release resources, close resources, etc. after the object is used.
6. Magic method:
PHP provides us with a series of functions starting with __. These functions do not need to be called manually,
will be automatically called at the right time. This type of function is called magic and is called a magic function.
eg:function __construct(){} is automatically called when a new object is created
function __destruct(){} is automatically called when the object is destroyed

We require that, except for magic methods, custom functions and methods cannot start with __.
Finally, generally for classes with more complex functions, we will write them into a separate class file.
The class file is named in the same lowercase, using the method of "class name lowercase.class.php".

When using this class in other files, you can use include to import this ".class.php" file.

## 2. Encapsulation and inheritance
######

1. What is encapsulation?
Through access modifiers, the properties and methods in the class that do not require external access are privatized to achieve access control.

*Note: It is to implement access control, not to deny access. In other words, after we privatize the attributes, we need to provide corresponding methods so that users can process the attributes through the methods we provide.

2. What is the role of encapsulation?
① Users only care about the functions that the class can provide, and do not care about the details of function implementation! (Encapsulation method)
② Control the user's data, prevent illegal data from being set, and control the data returned to the user (attribute encapsulation + set/get method)

3. Implement encapsulation operation?
①Method encapsulation
For some methods that are only used inside the class and are not provided for external use, then we can use private for such methods. Privatization process.
private function formatName(){} //This method can only be used within the class to call $this
function showName(){
$this -> formatName();
}
②Attribute encapsulation + set/get method
For control For setting and reading attributes, you can privatize the attributes and require users to set them through the set/get methods we provide
private $age;
function setAge($age){
$this->age=$age;
}
function getAge(){
return $this->age;
}
$Object->getAge();
$Object->setAge(12);

③Attribute encapsulation + magic method
private $age;
function __get($key){
return $this->$key;
}
function __set($key,$value){
$this->$key=$value;
}
$object ->age; //When accessing the private properties of the 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 object's private attributes, the __set() magic method is automatically called, and the set attribute name and attribute value are passed to the __set() method;

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

4. About the magic method of encapsulation:
①__set($key,$value): Automatically called when assigning values ​​to private properties of the class. When calling, pass two parameters to the method: The attribute name and value that need to be set.
②__get($key,$value): Automatically called when reading the private attributes of the class. When calling, pass a parameter to the method, the name of the attribute that needs to be read;
③__isset($key): Automatically called when the isset() function is used externally to detect private attributes.
>>>Use isset(); outside the class to detect private properties, which are not detected by default. false
>>>So, we can use the __isset(); function to return the internal detection result when automatically called.
function __isset($key){
return isset($this -> $key);
}
When external isset($object name->private attribute); is used for detection, the result returned by the above __isset() will be automatically called!

④__unset($key): Automatically called when the unset() function is used externally to delete private attributes;
function __unset($key){
unset($this -> $key);
}
When using unset($object name->private property externally) ); When deleting an attribute, the attribute name is automatically passed to __unset() and handed over to this magic method for processing.


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

2. Things to note when implementing inheritance?
① Subclasses can only inherit non-private properties of the parent class.
②After a subclass inherits a parent class, it is equivalent to copying the properties and methods of the parent class to the subclass, which can be called directly using $this.
③PHP can only inherit from one class and does not support one class inheriting multiple classes. But a class has multiple levels of inheritance.
class Person{}
class Adult extends Person{}
class Student extends Adult{}
//The Student class has the attributes and methods of both the Adult class and the Person class

3. Method override (method rewriting)
Conditions One: The subclass inherits the parent class
Condition two: The subclass overrides the existing method of the parent class

If it meets the above two conditions, it is called method overwriting . After overriding, when a subclass calls a method, the subclass's own method will be called.
Similarly, in addition to method overrides, subclasses can also have attributes with the same name as the parent class for attribute overrides.

If the subclass overrides the parent class method, how to call the parent class method with the same name in the subclass?

partent::method name();
Therefore, when a subclass inherits a parent class, it needs to be the first step in the construction of the subclass. , first call the parent class constructor to copy.

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

3. PHP keywords

1. final
①final modified class. This class is the final class and cannot be inherited!
②final modification method, this method is the final method and cannot be overridden!
③final cannot modify attributes.

2. static
① You can modify attributes and methods, which are called static attributes and static methods respectively, also called class attributes and class methods;
②Static properties and static methods can only be called directly using the class name.
Use "class name::$static property", "class name::static method()"
Person::$sex; Person::say( );
③Static properties and methods will be declared when the class is loaded and generated before the object.
④In static methods, non-static properties or methods cannot be called;
In non-static methods, static properties and methods can be called.
(Because static properties and methods have been generated when the class is loaded, non-static property methods have not been instantiated yet)
⑤In the class , you can use the self keyword to refer to the name of this class.
class Person{
static $sex = "nan";
function say(){
echo self::$sex;
}
}
⑥Static properties are shared, that is, new produces a lot Objects also share a property.

3. const keyword:
Declare constants in the class, not the define() function! The const keyword must be used.
Similar to the define() statement, the const keyword cannot be used to declare constants with $, and must be all capitalized!
Once a constant is declared, it cannot be changed. When calling, just like static, use the class name to call Person::constant.

4. Instanceof operator:
Detects whether an object is an instance of a certain class. (Including fathers, grandfathers, great-grandfathers...)
$zhangsan instanceof Person;

[Small summary] Several special operators
1. . can only connect strings; "".""
2. => When declaring an array, associate the key and value ["key"=> ;"value"]
3. -> The object (object from $this new) calls member properties and member methods;
4.::
①Use the parent keyword to call the method of the same name in the parent class: parent::say();
②Use the class name (and self) to call the static method in the class Properties, static methods, and constants.

4. Singleton

The singleton mode is also called the singleton mode.
It is guaranteed that a class can only have one object instance.

Implementation points:
① The constructor is private and the new keyword is not allowed to be used to create objects.
② Provide external methods to obtain objects, and determine whether the object is empty in the method.
If it is empty, create the object and return it; if it is not empty, return it directly.
③The attributes of the instance object and the method of obtaining the object must be static.
④ After that, objects can only be created using the static methods we provide.
eg:$s1 = Singleton::getSingle();

5. Object serialization and magic methods

***Keywords: clone and __clone, __antoload(), serialization and deserialization (serialization and deserialization), type constraints, magic method Summary (12)


1. Clone and __clone
1. When using = to talk about an object and assign it to another object , what is assigned is actually the address of the object.
Two objects point to the same address, so if one object changes, the other will also change.
eg: $lisi = $zhangsan;
2. If you want to completely clone one object into another object, the two objects are independent and mutually exclusive. If there is interference,
you need to use the clone keyword;
eg: $lisi = clone $zhangsan; //The two objects do not interfere with each other
3. __clone():
①When using the clone keyword to clone an object, the clone function is automatically called.
②__clone() function, similar to the constructor used when cloning, can assign an initial value to the new cloned object.
③$this in the __clone() function refers to the newly cloned object
In some versions, you can use $that to refer to the cloned object. In most cases, Not supported by most versions.
4. __toString()
When using echo and other output statements to directly print objects, call echo $zhangsan;
Then, You can specify the string returned by the __toString() function;
function __toString(){
return "haha";
}
echo $zhangsan; //The result is: haha

5, __call()
is not defined in the calling class or undisclosed method, the __call() method will be automatically executed.
During automatic execution, two parameters will be passed to the __call() method;
Parameter 1: The name of the called method
Parameter two: (array) parameter list of the calling method.

2. __antoload()
① This is the only magic method that is not used in the class;
② When When instantiating a non-existent class, this magic method is automatically called;
③When called, a parameter is automatically passed to __autoload(): the instantiated class name
So you can use this method to implement the function of automatically loading files.
function __autoload($className){
include "class/".strtolower($className).".class.php";
}
$zhangsan=new Person();//There is no Person class in this file, and __autoload() will be automatically executed to load the person.class.php file

3. Serialization and deserialization (serialization and deserialization)
1. Serialization: Convert the object into a character through a series of operations The process of stringing is called serialization;
(Objects record themselves by writing out numerical values ​​describing their status)
2. Deserialization: The process of converting a serialized string into an object is called deserialization;
3. When should serialization be used?
①When the object needs to be transmitted over the network
②When the object needs to be persisted in a file or database
4. How to implement serialization and deserialization
Serialization: $str=serialize($zhangsan);
Deserialization: $duixiang=unserialize ($str);
5. __sleep() magic method:
①When the object is serialized, the __sleep() function will be automatically executed;
②__sleep() function requires returning an array. The values ​​in the array are attributes that can be serialized; attributes that are not in the array cannot be serialized;
function __sleep(){
return array("name","age"); //Only the two attributes name/age can be serialized.
}

6. __wakeup() magic method
①When deserializing the object, it is automatically called_ _wakeup() method;
②When called automatically, it is used to reassign the new object attributes generated by deserialization.
function __wakeup(){
$this -> name = "李思";
}

4. Type constraints
1. Type constraints: refers to adding a data type to a variable to constrain that the variable can only store the corresponding data type.
(This operation is common in strongly typed languages. In PHP, only type constraints of arrays and objects can be implemented)
2. If the type constraint is a certain class, then objects of this class and subclasses of this class can pass.
3. In PHP, type constraints can only occur in the formal parameters of functions.
class Person{}
class Student extends Person{}
function func(Person $p){ //Constraint function Formal parameters, only accept Person class and Person subclass
echo "1111";
echo $p -> name;
}
func(new Person()); √
func(new Student()); √
func(" 111"); ×

Form like new Person();, we call it "anonymous object"; ※Base class: parent class

※※※Derived class: subclass

5. Summary of magic methods
1. __construct(): Constructor, automatically called when new an object.
2. __destruct(): Destructor, automatically called before an object is destroyed.
3. __get(): Automatically called when accessing private properties in the class. Pass the read attribute name and return $this->attribute name
4. __set(): Automatically called when assigning a value to a private attribute of the class. Pass the attribute name and attribute value that need to be set;
5. __isset(): Automatically called when using isset() to detect the private attributes of the object. Pass the detected attribute name and return isset($this -> attribute name);
6. __unset(): Automatically called when using unset() to delete the object's private attributes. Pass the deleted attribute name, and execute unset($this -> attribute name);
7 in the method. __toString(): Automatically called when using echo to print the object. Return the content you want to display when printing the object; the return must be a string;
8, __call(): Automatically called when calling an undefined or unpublicized method in a class. Pass the called function name and parameter list array;
9. __clone(): Automatically called when cloning an object using the clone keyword. Its function is to initialize and assign values ​​to the newly cloned object;
10. __sleep(): automatically called when the object is serialized. Returns an array, and the values ​​in the array are attributes that can be serialized;
11. __wakeup(): automatically called when the object is deserialized. To deserialize the newly generated object, perform initialization and assignment;
12. __autoload(): The function needs to be declared outside the class. Automatically called when an undeclared class is instantiated. By passing the instantiated class name, the corresponding class file can be automatically loaded using the class name.

1. What is an abstract method?
Methods without method body {} must be modified with the abstract keyword. Such methods are called abstract methods.
abstract function say(); //Abstract method

2. What is an abstract class?
A class modified with the abstract keyword is an abstract class.
abstract class Person{}

3. Notes on abstract classes:
① Abstract classes can contain non-abstract classes Method;
② The class containing abstract method must be an abstract class, and the abstract class does not necessarily have to contain abstract method;
③ Abstract class cannot be instantiated. (Abstract classes may contain abstract methods. Abstract methods have no method bodies, and instantiation calls are meaningless)
The purpose of using abstract classes is to limit instantiation! ! !

4. If a subclass inherits an abstract class, then 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 using abstract classes?
① Limit instantiation. (An abstract class is an incomplete class. The abstract method inside has no method body, so it cannot be instantiated)
② Abstract class provides a specification for the inheritance of subclasses, and subclasses inherit an abstraction Class must contain and implement the abstract methods defined in the abstract class.

## 6. Abstract classes and abstract methods

1. Interface
1. What is an interface?
An interface is a specification that provides a set of method combinations that must be implemented by a class that implements the interface.
The interface is declared using the interface keyword;
interface Inter{}

2. All methods in the interface must They are all abstract methods.
Abstract methods in interfaces do not need and cannot be modified with abstract.

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

4. Interfaces can inherit interfaces and use the extends keyword!
The interface uses extends to inherit the interface, which can achieve multiple inheritance.
interface int1 extends Inter,Inter2{}

5. Classes can implement interfaces, using the implements keyword!
The class uses implements to implement the interface, and can implement multiple interfaces at the same time. Multiple interfaces are separated by commas;
abstract class Person implements Inter,Inter2{}
A class implements one or more interfaces, then this class must implement all abstract methods in all interfaces!
Unless this class is an abstract class.

※[Difference between interface && abstract class]
1. In terms of declaration method, interface uses the interface keyword and abstract class uses abstract class.
2. In terms of implementation/inheritance, a class uses extends to inherit an abstract class and implements to implement the interface.
3. Abstract classes can only be inherited in a single way, and interfaces can be implemented in multiple ways. (Interface extends interface), multiple implementations (class implements interface)
4. Abstract classes can have non-abstract methods, and interfaces can only have abstract methods, not abstract methods.
Abstract methods in abstract classes must be modified with the abstract keyword, and abstract methods in interfaces cannot be modified with modifiers.
5. An abstract class is a class that can have attributes and variables; the interface can only have constants.

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 polymorphism.

2. Necessary ways to achieve polymorphism:
① Subclass inherits parent class;
② Subclass repeats Write the parent class method;
③ The parent class reference points to the child class object


## 7. Interface and Polymorphism

The above is the detailed content of Detailed explanation of my understanding of object-oriented in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!