Home Backend Development PHP Tutorial Share knowledge about some commonly used methods in php

Share knowledge about some commonly used methods in php

Jun 23, 2017 pm 03:20 PM
php abstract method static

Foreword

## OOP

I have been studying PHP for a long time. Today I will summarize the abstract classes and abstract methods in PHP/static properties and static methods/single interest mode (monomorphic mode) in PHP/serialization and deserialization. Rowization (serialization and deserialization).

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

2, what is an abstract class?
A class that contains abstract methods is called an abstract class. Abstract classes must be modified with the abstract keyword.
abstract class person {}
## 3. Precautions for abstract categories
① Abstract class can include non -abstract methods; #Does not necessarily include abstract methods;
③ abstract classes, cannot be instantiated.
(The abstract class may include abstract methods, abstract methods have no method, instantiated calls are meaningless.)

The purpose of using abstract class! Just limit instantiation! ! !​​ ​

​ ​ 4. If a subclass inherits an 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 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. If a subclass inherits an abstract class, it must include and implement the abstract methods defined in the abstract class.
             
         

 

##1 Abstract classes and abstract methods in PHP
##2 Static properties and static methods

 
   1. static
    ① You can modify attributes and methods, which are called static attributes and static methods respectively, also called class attributes and class methods; name directly.
Use the "class name :: $ static attributes", "class name :: static method ()"
Person :: $ sex; person ::);
③ Static attributes, methods, in It is declared when the class is loaded. Preliminate to the object;
④ Static method, non -static attributes or methods cannot be called;
Non -static method, you can call static attributes or methods; Generated, rather than a static attribute method, no instantiation has been born yet)
        ⑤ In a class, you can use the self keyword to refer to the class name.
Class Person {
Static $ Sex = "nan";
Function say () {
Echo Self :: $ sex;
}
⑥ Static attributes are shared. That is to say, many new objects also share the same attribute.

2. final
① final modified class, this class is the final class and cannot be inherited;
② final modified method, this method is the final method and cannot be overridden!
③ Final properties cannot be modified.
                      3. const keyword;
                  When declaring constants in a class, you cannot use the define() function! You must use the const keyword.
and define () are similar to the state, the const keyword declaration cannot be brought with $, and all of them must be uppercase!
              Once a constant is declared, it cannot be changed. When calling, it is the same as static, using the class name Person:: constant.
 
    [Small summary] Several special operators
  1. .   can only connect strings; "".""
  2. => declares that the array is associated with the key and value [" key"=>"value"]
3. -> Object (object generated by $this new) uses member attributes 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 properties, static methods, and constant.






##3 Single interest mode in PHP (monomorphic mode )

  
 Simple interest mode is also called monomorphic pattern
                              
   by        
    
                        
                       
           
    
    because it can be guaranteed that a class can only have one object instance.

Implementation points:
① The constructor is privatized, and it is not allowed to use the new keyword to create objects.
          ② Provide external methods to obtain objects. In the method, determine whether the object is empty. If it is empty, create the object and return it. If it is not empty, put it back directly.

    ③ The attributes of the instance object and the methods of the past objects must be static.

          ④ After that, you can only use the static methods we provide to create objects. $s1 = Singleton::getSingle();
                                                                                                                                 

##4 Serialization and Deserialization (Serialization ization and deserialization)

  
                        1. Serialization: The process of converting an object into a string through a series of operations is called serialization; The process of converting a string into an object is called deserialization;
3. When is serialization used?
① When the object needs to be transmitted in the network;
② The object needs to be saved for a long time in the file or database;
4. How to achieve the serialization and anti -stringing of the object?
         Serialization: $str = serialize($duixiang);
           Deserialization:  $duixiang = unserialize($str); when executing When the object is serialized, the __sleep() function will be automatically executed;
              ② The __sleep() function is required to return an array. The values ​​in the array are attributes that can be serialized; attributes that are not in the array cannot be Serialization;
Function __sleep () {
Return Array ("name", "Age"); // Only name/Age can be serialized
}
6, __ wakeupup ()Magic method:
          ① When deserializing an object, the __wakeup() method is automatically called;
            ② When called automatically, it is used to re-copy the new object attributes generated by deserialization;
                     function __wakeup(){
                                                                                                                                                                                                    

5 Constraint type

  
1. Type constraint: refers to adding a data type before 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 Can realize type constraints of arrays and objects)
2. If the type constraint is a certain class, this class and subclass objects of this class can pass;
 
3. In PHP, type Constraints can only occur in formal parameters of functions.
class Person{}
class Student extend

function func(Person $p){
//Constraint function parameters, only accept Person class and Person subclass
echo " 111 "
Echo $ P-& GT; name;
}
Func (New Person ()); √
Func (New Student ()); √
Func (" 111 " );



##6 Summary of magic methods

7. __toString(): Automatically called when using echo to print the object. Return the actual content when you want to print 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. The function is to initialize and copy the newly cloned object;
##  1 , __construct(): Constructor, automatically called when new an object 2. __destruct(): Destructor, automatically called before an object is destroyed
3. __get(): Access private information in the class attribute, automatically called. 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) in the method;
10. __sleep(): Automatically called when the object is serialized. Returns an array whose values ​​are serializable properties.
11. __wakeup(): Automatically called when the object is deserialized. To deserialize the newly generated object, perform initialization copy;
12. __autoload(): The function needs to be declared outside the class. Automatically called when instantiating a live class. By passing the instantiated class name, the corresponding class file can be automatically loaded using the class name.
 
   

 

 

 

There may be some errors in the notes taken while studying, and you are welcome to criticize and give me some advice.

Reflect, review, gain a little bit every day--------------------- Looking forward to a better self

The above is the detailed content of Share knowledge about some commonly used methods in php. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles