Practical basic knowledge of PHP object-oriented

炎欲天舞
Release: 2023-03-14 16:14:01
Original
1612 people have browsed it


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 alphanumeric and underline characters. 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 may not have 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?
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调用
function showName(){
    $this -> formatName();
}
Copy after login

②Attribute encapsulation + set/get method
In order to control the setting and reading of attributes, you can Privatize the attributes and require users to set them through the set/get methods we provide


 private $age;
 //set方法
 function setAge($age){
     $this->age=$age;
 }
 //get方法
 function getAge(){
     return $this->age;
 }
Copy after login

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

③Attribute encapsulation + magic method


private $age;
function __get($key){
return $this->$key;
}
function __set($key,$value){
$this->$key=$value;
}
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 attributes of the object, automatically call the __set() magic method, and pass the set attribute name and attribute value 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.


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

When external isset($object name->private attribute); is used for detection, the above __isset() return will be automatically called result!

④__unset($key): Automatically called when the unset() function is used externally to delete private attributes;
1 function __unset($key){ 2 unset($this -> $key); 3 }
When the attribute is deleted externally using unset($object name->private attribute); , automatically pass the attribute name to __unset(), and hand it over to this magic method for processing.


继承的基础知识:

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::方法名();
所以,当子类继承父类时,需在子类的构造中的第一步,首先调用父类构造进行复制。


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

三、PHP关键字

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

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


 class Person{
     static $sex = "nan";
     function say(){
         echo self::$sex;
     }
 }
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()函数返回的字符串;


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

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

__antoload()


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


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

Object-oriented serialization and deserialization (serialization and deserialization)


1. Serialization: The process of converting an object into a string through a series of operations is called serialization.

                                     cast through through through through a value to describe its own status. Serialization: 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.

1 function
__wakeup(){ 2 $this -> ; name = "李思"; 3 } ##四

Type constraint

1. Type constraints: refers to adding the data type to the variable to constrain that the variable can only be stored The corresponding data type.


(This operation is common in strongly typed languages. In PHP, only type constraints for arrays and objects can be implemented) 2,
If the type constraint is a certain class, 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){ //约束函数的形参,只接受Person类及Person子类
     echo "1111";
     echo $p -> name;
 }
Copy after login

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

形如new Person();的形式,我们称其为"匿名对象";

※※※基类:父类    
※※※派生类:子类

魔术方法小总结


1、__construct():构造函数,new一个对象时,自动调用。
2、__destruct():析构函数,当一个对象被销毁前,自动调用。
3、__get():访问类中私有属性时,自动调用。传递读取的属性名,返回$this->属性名
4、__set():给类的私有属性赋值时,自动调用。传递需要设置的属性名和属性值;
5、__isset():使用isset()检测对象私有属性时,自动调用。传递检测的属性名,返回isset($this -> 属性名);
6、__unset():使用unset()删除对象私有属性时,自动调用。传递删除的属性名,方法中执行unset($this -> 属性名);
7、__toString():使用echo打印对象时,自动调用。返回想要在打印对象时,显示的内容;返回必须是字符串;
8、__call():调用一个类中未定义或未公开的方法时,自动调用。传递被调用的函数名,和参数列表数组;
9、__clone():当使用clone关键字,克隆一个对象时,自动调用。作用是为新克隆的对象进行初始化赋值;
10、__sleep():对象序列化时,自动调用。返回一个数组,数组中的值就是可以序列化的属性;
11、__wakeup():对象反序列化时,自动调用。为反序列化新产生的对象,进行初始化赋值;
12、__autoload():需要在类外部声明函数。当实例化一个未声明的类时,自动调用。传递实例化的类名,可以使用类名自动加载对应的类文件。

 

六、抽象类和抽象方法

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.

Interface


1. What Is it 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, the interface key is to use interface Word, abstract class uses 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

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 overrides parent class method;
③ The parent class reference points to the subclass object

## 7. Interface and Polymorphism

The above is the detailed content of Practical basic knowledge of PHP object-oriented. 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