Home  >  Article  >  Backend Development  >  Why are PHP's __get and __set magic methods not invoked when accessing a public property?

Why are PHP's __get and __set magic methods not invoked when accessing a public property?

Barbara Streisand
Barbara StreisandOriginal
2024-11-25 19:59:15812browse

Why are PHP's __get and __set magic methods not invoked when accessing a public property?

Magic Methods __get and __set in PHP

PHP provides magic methods that enable developers to overload certain operations, such as property access and method calls. Among these methods are __get and __set, which are designed to override the default behavior of property access.

The provided code defines a class foo with public properties and magic methods __get and __set. However, when attempting to use these methods to access $foo->bar, only the public property is being accessed.

This is because __get and __set are invoked only when the property or method is inaccessible. Since $foo->bar is a public property, the magic methods are not triggered.

As per the PHP manual, __get is executed when reading data from inaccessible properties, and __set is used when writing data to inaccessible properties. In this case, the class members are public and therefore accessible, making the magic methods irrelevant.

Instead of using magic methods, consider implementing proper getters and setters or directly accessing the properties for more efficient and predictable behavior. Magic methods should be reserved for exceptional cases where properties or methods are inaccessible by normal means.

The above is the detailed content of Why are PHP's __get and __set magic methods not invoked when accessing a public property?. 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