search
HomeBackend DevelopmentPHP TutorialShare knowledge about some commonly used methods in php

Share knowledge about some commonly used methods in php

Jun 23, 2017 pm 03:20 PM
phpabstractmethodstatic

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
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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version