Home  >  Article  >  Backend Development  >  PHP magic functions revealed

PHP magic functions revealed

WBOY
WBOYOriginal
2024-06-02 18:35:01612browse

In PHP, magic functions provide additional behaviors for objects, enhancing the readability and maintainability of the code. These functions are automatically called when objects are created, accessed, compared, and destroyed. Common magic functions include: __construct(): used to initialize properties when creating a new object. __destruct(): used to clean up resources when destroying objects. __get() and __set(): Called when accessing or setting properties that do not exist. __call(): Called when calling a method that does not exist. __toString(): Called when forcing the object to be converted to a string.

PHP magic functions revealed

PHP Magic Function Revealed

In PHP, magic functions give objects special behaviors and enhance the readability of the code. performance and maintainability. They are called automatically when objects are created, accessed, compared, and destroyed.

Common magic functions

  • __construct(): Called when creating a new object, used to initialize properties.
  • __destruct(): Called when the object is destroyed, used to clean up resources.
  • __get() and __set(): Called when accessing or setting a non-existent property.
  • __call(): Called when calling a method that does not exist.
  • __toString(): Called when the object is cast to a string.

Practical case

Use __construct() to initialize the object

class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$person = new Person('John Doe', 30);
echo $person->name; // 输出:John Doe

Use __destruct( ) Clean up resources

class Database {
    private $connection;

    public function __construct() {
        $this->connection = new MongoClient();
    }

    public function __destruct() {
        $this->connection->close();
    }
}

$db = new Database();
// 脚本执行完毕后,连接会被自动释放

Use __get() and __set() to access and set dynamic properties

class MyClass {
    private $data = [];

    public function __get($name) {
        return $this->data[$name] ?? null;
    }

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

$obj = new MyClass();
$obj->test = 'foo';
echo $obj->test; // 输出:foo

The above is the detailed content of PHP magic functions revealed. 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