Home > Backend Development > PHP Tutorial > Talk about my understanding of object-oriented in php

Talk about my understanding of object-oriented in php

零下一度
Release: 2023-03-12 14:08:01
Original
5557 people have browsed it

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 distinguish between object-oriented and process-oriented.

Object-oriented programming (OOP) is a basic skill in our programming. PHP5 provides good support for OOP. How to use OOP ideas to perform advanced programming of PHP is very meaningful for improving PHP programming capabilities and planning a good Web development architecture. Below we will use examples to illustrate the practical significance and application methods of using PHP's OOP for programming.

When we usually build a website with a database backend, we will consider that the program needs to be suitable for different application environments. What is different from other programming languages ​​is that in PHP, a series of specific functions are used to operate the database (if you do not use the ODBC interface). Although this is very efficient, the encapsulation is not enough. If there is a unified database interface, then we can apply it to a variety of databases without making any modifications to the program, thus greatly improving the portability and cross-platform capabilities of the program.

Let me introduce to you their differences:

Object-oriented focuses on which object handles a problem.

Its biggest feature is that it consists of classes with attributes and functions one by one, and gets objects from the classes to solve problems.

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

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.

##二Declaration and instantiation of classes

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 letters, numbers and underscores. It cannot start with a number and must comply with the big camel case rule;
② The class name must be modified with class, followed by the class name There must not be ();
③Attributes must have access modifiers, and methods do not need access modifiers.

3. Calling instantiated objects and object attribute methods:
$Object name = new class name(); //() You can call properties and methods from outside the class without

:
$object name-> $property name; //Use ->When calling attributes, the attribute name cannot contain the $ symbol

Calling attributes and methods within the class:
$this -> $ Attribute name;

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 the constructor:
①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?
Use access modifiers to privatize the properties and methods in the class that do not require external access 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.

1 private function formatName(){} //这个方法仅仅能在类内部使用$this调用2 function showName(){3 $this -> formatName();4 }
Copy after login

②Attribute encapsulation + set/get method
In order to control the setting and reading of attributes, the attributes can be Privatize the process and require the user to set it through the set/get method we provide

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

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

③Attribute encapsulation + magic method

    __get(  ->   __set(, ->= }
Copy after login

$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 private properties of the object, the __set() magic method is automatically called, and the set property name and 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): When assigning values ​​to class private attributes Automatically call, pass two parameters to the method when calling: the attribute name that needs to be set, and the attribute value.
②__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.

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

当外部使用isset($对象名->私有属性);检测时,将自动调用上述__isset()返回的结果!

④__unset($key):外部使用unset()函数删除私有属性时,自动调用;
 1 function __unset($key){ 2 unset($this -> $key); 3 } 
当外部使用unset($对象名->私有属性);删除属性时,自动将属性名传给__unset(),并交由这个魔术方法处理。

 

继承的基础知识:

1、如何实现继承?
给子类使用extends关键字,让子类继承父类;
class Student extends Person{}

2、实现继承的注意事项?
①子类只能继承父类的非私有属性。
②子类继承父类后,相当于将父类的属性和方法copy到子类,可以直接使用$this调用。
③PHP只能单继承,不支持一个类继承多个类。但是一个类进行多层继承。
class Person{}
class Adult extends Person{}
class Student extends Adult{}
//Student 类就同时具有了Adult类和Person类的属性和方法

3、方法覆盖(方法重写)
条件一: 子类继承父类
条件二:子类重写父类已有方法

符合上述两个条件,称为方法覆盖。覆盖之后,子类调用方法,将调用子类自己的方法。
同样,除了方法覆盖,子类也可以具有与父类同名的属性,进行属性覆盖。

如果,子类重写了父类方法,如何在子类中调用父类同名方法?

partent::方法名();
所以,当子类继承父类时,需在子类的构造中的第一步,首先调用父类构造进行复制。

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

 

三、PHP关键字

 

1、final
①final修饰类,此类为最终类,不能被继承!
②final修饰方法,此方法为最终方法,不能被重写!
③final不能修饰属性。

2、static
①可以修饰属性和方法,分别称为静态属性和静态方法,也叫类属性,类方法;
②静态属性,静态方法,只能使用类名直接调用。
使用"类名::$静态属性" , "类名::静态方法()"
Person::$sex;   Person::say();
③静态属性和方法,在类装载时就会声明,先于对象产生。
④静态方法中,不能调用非静态属性或方法;
非静态方法,可以调用静态属性和方法。
(因为静态属性和方法在类装载时已经产生,而非静态的属性方法,此时还没有实例化诞生)
⑤在类中,可以使用self关键字,代指本类名。

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

⑥静态属性是共享的,也就是new出很多对象,也是共用一个属性。

3、const关键字:
在类中声明常量,不能是define()函数!必须使用const关键字。
与define()声明相似,const关键字声明常量不能带$,必须全部大写!
常量一旦声明,不能改变。调用时与static一样,使用类名调用Person::常量。

4、instanceof操作符:
检测一个对象,是否是某一个类的实例。(包括爹辈,爷爷辈,太爷爷辈……)

$zhangsan instanceof Person;
Copy after login

 

【小总结】几种特殊操作符

.  只能连接字符串; "".""
=> 声明数组时,关联键与值["key"=>"value"]
-> 对象($this new出的对象)调用成员属性,成员方法;
④ :: ①使用parent关键字,调用父类中的同名方法:parent::say();
      ②使用类名(和self)调用类中的静态属性,静态方法,以及常量。


 

四、单例

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

 

***关键词:clone与__clone、__antoload()、串行化与反串行化(序列化与反序列化)、类型约束、魔术方法小总结(12个)

 

clone与__clone


1、当使用=讲一个对象,赋值给另一个对象时,赋的实际是对象的地址。
两个对象指向同一地址,所以一个对象改变,另一个也会变化。
eg: $lisi = $zhangsan;
2、如果想要将一个对象完全克隆出另一个对象,两个对象是独立的,互不干扰的,
则需要使用clone关键字;
eg: $lisi = clone $zhangsan; //两个对象互不干扰
3、__clone():
①当使用clone关键字,克隆对象时,自动调用clone函数。
②__clone()函数,类似于克隆时使用的构造函数,可以给新克隆对象赋初值。
③__clone()函数里面的$this指的是新克隆的对象
某些版本中,可以用$that代指被克隆对象,绝大多数版本不支持。
4、__toString()
当使用echo等输出语句,直接打印对象时调用echo $zhangsan;
那么,可以指定__toString()函数返回的字符串;

1 function __toString(){2 return "haha";3 }4 echo $zhangsan; //结果为:haha
Copy after login

5、__call()
调用类中未定义或未公开的方法时,会自动执行__call()方法。
自动执行时,会给__call()方法传递两个参数;
参数一:调用的方法名
参数二:(数组)调用方法的参数列表。

 

__antoload()


①这是唯一一个不在类中使用的魔术方法;
②当实例化一个不存在的类时,自动调用这个魔术方法;
③调用时,会自动给__autoload()传递一个参数:实例化的类名
所以可以使用这个方法实现自动加载文件的功能。

1 function __autoload($className){2 include    "class/".strtolower($className).".class.php";3 }4 $zhangsan=new Person();//本文件内没有Person类,会自动执行__autoload()加载person.class.php文件
Copy after login

 

面向对象串行化与反串行化(序列化与反序列化)


1、串行化:将对象通过一系列操作,转化为一个字符串的过程,称为串行化。

     (对象通过写出描述自己状态的数值来记录自己)

2、反串行化:将串行化后的字符串,再转为对象的过程,称为反串行化;
3、什么时候使用串行化?
①对象需要在网络中传输的时候
② 对象需要在文件或数据库中持久保存的时候
4、怎样实现串行化与反串行化
串行化:  $str=serialize($zhangsan);
反串行化:$duixiang=unserialize($str);
5、__sleep()魔术方法:
①当执行对象串行化的时候,会自动执行__sleep()函数;
②__sleep()函数要求返回一个数组,数组中的值,就是可以串行化的属性;不在数组中的属性,不能被串行化;
function __sleep(){
return array("name","age"); //只有name/age两个属性可以串行化。
}

6、__wakeup()魔术方法
①当反串行化对象时,自动调用__wakeup()方法;
②自动调用时,用于给反串行化产生的新对象属性,进行重新赋值。
 1 function __wakeup(){ 2 $this -> name = "李四"; 3 } 

类型约束


1、类型约束:是指在变量时,加上数据类型,用于约束此变量只能存放对应的数据类型。
(这种操作常见于强类型语言,在PHP中,只能实现数组和对象的类型约束)
2、如果类型约束为某一个类,则本类以及本类的子类对象,都可以通过。
3、在PHP中,类型约束,只能发生在函数的形参中。

1 class Person{}2 class Student extends Person{}3 function func(Person $p){ //约束函数的形参,只接受Person类及Person子类4 echo "1111";5 echo $p -> name;6 }
Copy after login

func(new Person());
func(new Student());
func("111"); ×

##Form like new Person();, we call it "anonymous object";

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

Summary of magic methods

##1. __construct(): Constructor, when new an object, Automatically called.
2. __destruct(): The destructor is 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


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, Interface All methods in must be 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, Interface can inherit the interface, use the extends keyword!
The interface uses extends to inherit the interface, which can achieve multiple inheritance.
interface int1 extends Inter,Inter2{}

5. The class can implement the interface, 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]:

①In terms of declaration method, interfaces use the interface keyword and abstract classes use abstract class.
②In terms of implementation/inheritance, a class uses extends to inherit an abstract class and implements to implement the interface.
③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)
④Abstract classes can have non-abstract methods, 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.
⑤An abstract class is a class that can have attributes and variables; the interface can only have constants.

Polymorphism

##II. 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 subclass object

## 7. Interface and Polymorphism

The above is the detailed content of Talk about 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