search
HomeBackend DevelopmentPHP TutorialMagic Methods: Understanding __construct, __destruct and other core methods in PHP

Magic methods: Understanding core methods such as __construct and __destruct in PHP

In the PHP language, there are some special methods called "magic methods", including __construct, __destruct, etc. These methods play an important role in object-oriented programming in PHP. This article will explain the role and practical application of these methods.

__construct method

__construct method is a very important method. It is a method that is automatically called when PHP creates a new object. In this method, we can perform some initialization work, such as setting default values ​​for the properties of the object, connecting to the database, etc. Moreover, if we do not define this method, an error will occur when the class is instantiated.

The following is a sample code:

class Person{
  public $name;
  public $age;
  
  function __construct($name, $age){
    $this->name = $name;
    $this->age = $age;
  }
  
  function showInfo(){
    echo "姓名:" . $this->name . " 年龄:" . $this->age;
  }
}

$person = new Person("张三", 20);
$person->showInfo();

In the above code, we define a class named Person and define a __construct method in the class to initialize the name and Age attribute. When instantiating the Person class, we pass in "Zhang San" and 20 as parameters, so that personal information can be output through the $person->showInfo() method.

__destruct method

__destruct method is a method that is automatically called when the object is destroyed. In this method, we can perform some cleanup work, such as releasing some occupied resources, etc. Similarly, if we do not define this method, an error will occur when the object is destroyed.

The following is a sample code:

class Car{
  public $brand;
  
  function __construct($brand){
    $this->brand = $brand;
  }
  
  function run(){
    echo "我开着" . $this->brand . "在马路上飞奔!";
  }
  
  function __destruct(){
    echo $this->brand . "被销毁了!";
  }
}

$car = new Car("宝马");
$car->run();

In the above code, we define a class named Car, and define a __destruct method in the class to output and destroy a certain vehicle information. After we instantiate the Car class, we call the $car->run() method to output the vehicle information, and output the destruction information at the end.

__call method

__call method is a method that is automatically called when a method that does not exist in the class is called. In this method, we can dynamically call a method and pass parameters. This method is very suitable for dealing with some uncertain situations during development, such as dynamically calling database operation methods.

The following is a sample code:

class Database{
  private $db;
  
  function __construct($host, $user, $password, $dbName){
    $this->db = new mysqli($host, $user, $password, $dbName);
  }
  
  function __call($method, $args){
    if(method_exists($this->db, $method)){
      return call_user_func_array([$this->db, $method], $args);
    }else{
      die("没有找到" . $method . "方法!");
    }
  }
}

$database = new Database("localhost", "root", "password", "test");
$res = $database->query("SELECT * FROM users");

while($row = $res->fetch_assoc()){
  echo $row['name'];
}

In the above code, we define a class named Database and define a __call method in the class for dynamic calling Methods of the mysqli class. When we instantiate the Database class and call the query method, the query() method in the mysqli class is actually called dynamically.

Conclusion

In the PHP language, magic methods provide us with many useful tools, such as the __construct method for initializing objects, the __destruct method for cleanup, and the __call method for implementation Dynamically calling methods, etc. Proficiency in these methods is very important for object-oriented programming in PHP.

The above is the detailed content of Magic Methods: Understanding __construct, __destruct and other core 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
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)