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