Home > Backend Development > PHP Tutorial > What are the magic methods in PHP?

What are the magic methods in PHP?

WBOY
Release: 2024-06-03 17:50:08
Original
735 people have browsed it

Magic methods in PHP are special methods that are triggered by specific events, such as object creation, property access, and method invocation. Common magic methods include: __construct() (object creation), __destruct() (object destruction), __get() (no attribute access), __set() (no attribute setting), __isset() (check whether the attribute exists) ), __unset() (attribute clearing), __call() (undefined method call), __callStatic() (undefined static method call).

What are the magic methods in PHP?

Magic methods in PHP

What are magic methods?

Magic methods are special methods defined in PHP classes that are triggered by specific events, such as object creation, property access, and method invocation.

Common magic methods in PHP:

  • __construct(): Called when the object is created.
  • __destruct(): Called when the object is destroyed.
  • __get(): Called when accessing a property that does not exist.
  • __set(): Called when setting a non-existent property.
  • __isset(): Called when checking whether the attribute exists.
  • __unset(): Called when clearing attributes.
  • __call(): Called when calling an undefined method.
  • __callStatic(): Called when an undefined static method is called.

Practical case:

Consider a class representing books:

class Book {
    private string $title;
    private int $pages;

    public function __construct(string $title, int $pages) {
        $this->title = $title;
        $this->pages = $pages;
    }
Copy after login

The above is the detailed content of What are the magic methods in PHP?. 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