Home Backend Development PHP Tutorial Magic Methods: Understanding __construct, __destruct and other core methods in PHP

Magic Methods: Understanding __construct, __destruct and other core methods in PHP

Jun 19, 2023 pm 11:22 PM
magic method __construct __destruct

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();
Copy after login

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();
Copy after login

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'];
}
Copy after login

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 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Decrypting Python metaprogramming: from basics to advanced paradigms Decrypting Python metaprogramming: from basics to advanced paradigms Feb 19, 2024 pm 03:30 PM

Python metaprogramming basics Python metaprogramming is the ability to dynamically manipulate Python code, which makes Python a very powerful language. Metaprogramming can be implemented in the following ways: Class decorator: A class decorator is a decorator that modifies the definition of a class. It can be used to add or modify the properties and methods of a class, and can also be used to control the instantiation process of a class. defadd_method_to_class(cls):defnew_method(self):print("Thisisanewmethod")setattr(cls,"new_method",new_method)returncls@a

How to follow the execution order of PHP magic methods? How to follow the execution order of PHP magic methods? Apr 17, 2024 pm 09:33 PM

The execution order of PHP magic methods follows the following rules: magic methods with high priority are executed first. If both the subclass and the parent class define magic methods with the same name, the magic method of the subclass will be executed first. If a class defines both a regular method and a magic method with the same name, the regular method will be executed first.

What is a magic method? How to use it in Laravel What is a magic method? How to use it in Laravel Sep 26, 2022 pm 08:21 PM

What is a magic method? How to use it in Laravel? The following article will introduce to you how to apply PHP magic methods in Laravel. I hope it will be helpful to you!

PHP development: Use reflection and magic methods to achieve automatic code generation and dynamic calling PHP development: Use reflection and magic methods to achieve automatic code generation and dynamic calling Jun 15, 2023 pm 04:16 PM

In PHP development, reflection and magic methods are two commonly used techniques. When we need to automatically generate code or dynamically call certain functions, reflection and magic methods can make our code more flexible and efficient. In this article, we will explore how to use reflection and magic methods to achieve automatic code generation and dynamic invocation. Reflection is a powerful tool provided by PHP, which can help us obtain information such as classes, methods, and properties when the program is running. Through reflection, we can dynamically obtain information such as methods, properties, and annotations of a class or object, so that

Magic methods for PHP functions Magic methods for PHP functions May 19, 2023 am 08:06 AM

PHP is a server-side scripting language developed based on C language, which is widely used in web development. Functions are one of the most basic and commonly used components in programs. PHP also provides many magic methods related to functions, which can help developers better take advantage of functions. In this article, we will introduce the magic methods of PHP functions and their usage. __construct()__construct() is one of the most commonly used magic methods in PHP. It is automatically called when creating an object for initialization.

Take you through 16 PHP magic methods Take you through 16 PHP magic methods May 16, 2022 pm 08:45 PM

What is a magic method? This article will take you through 16 magic methods that PHP developers must know and know. I hope it will be helpful to you!

Magic Methods: Understanding __construct, __destruct and other core methods in PHP Magic Methods: Understanding __construct, __destruct and other core methods in PHP Jun 19, 2023 pm 11:22 PM

Magic methods: Understand 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 in PHP

PHP Expert Tips: Master Hidden Functions and Magic Methods PHP Expert Tips: Master Hidden Functions and Magic Methods May 09, 2024 am 10:09 AM

Hidden functions and magic methods in PHP, such as CLASS and __call(), provide powerful capabilities to enhance code flexibility: hidden functions perform special operations, such as obtaining namespaces and file paths. Magic methods handle special cases such as undefined method calls. Custom exception handling and simplified property reading are practical examples. Use these tips to write more flexible and concise PHP code.

See all articles