Table of Contents
php magic method - attribute overloading method, php magic attribute overloading
Home Backend Development PHP Tutorial PHP magic method - attribute overloading method, PHP magic attribute overloading_PHP tutorial

PHP magic method - attribute overloading method, PHP magic attribute overloading_PHP tutorial

Jul 12, 2016 am 08:57 AM

php magic method - attribute overloading method, php magic attribute overloading

php has a very magical method. These methods are reserved methods and are usually not used externally. Explicitly called, they start with a double underscore (__), and they are called Magic Methods. PHP officials do not recommend defining other methods starting with double underscores.

This time we introduce the attribute overloading method: get/set/isset/unset

<span>public</span> void __set ( <span>string</span> <span>$name</span> , <span>mixed</span> <span>$value</span><span> )

</span><span>public</span> <span>mixed</span> __get ( <span>string</span> <span>$name</span><span> )

</span><span>public</span> bool __isset ( <span>string</span> <span>$name</span><span> )

</span><span>public</span> void __unset ( <span>string</span> <span>$name</span> )
Copy after login

These methods are triggered when accesses inaccessible properties .

As follows:

<span> 1</span> <?<span>php
</span><span> 2</span> 
<span> 3</span> <span>class</span><span> Cls{
</span><span> 4</span> 
<span> 5</span>     <span>private</span> <span>$a</span> = 0<span>;
</span><span> 6</span>     <span>protected</span> <span>$b</span> = 1<span>;
</span><span> 7</span>     <span>public</span> <span>$c</span> = 2<span>;
</span><span> 8</span>     <span>var</span> <span>$d</span> = 3<span>;
</span><span> 9</span> 
<span>10</span>     <span>private</span> <span>$_properties</span> = <span>array</span>(0<span>);
</span><span>11</span> 
<span>12</span>     <span>public</span> <span>function</span> __set(<span>$name</span>, <span>$value</span><span>){
</span><span>13</span>         <span>echo</span> <span>__METHOD__</span> . ' is called! ' . json_encode(<span>func_get_args</span>()) . "\n"<span>;
</span><span>14</span>         <span>return</span> <span>$this</span>->_properties[<span>$name</span>] = <span>$value</span><span>;
</span><span>15</span> <span>    }
</span><span>16</span> 
<span>17</span>     <span>public</span> <span>function</span> __get(<span>$name</span><span>){
</span><span>18</span>         <span>echo</span> <span>__METHOD__</span> . ' is called! ' . json_encode(<span>func_get_args</span>()) . "\n"<span>;
</span><span>19</span>         <span>return</span> <span>$this</span>->_properties[<span>$name</span><span>];
</span><span>20</span> <span>    }
</span><span>21</span> 
<span>22</span>     <span>public</span> <span>function</span> __isset(<span>$name</span><span>){
</span><span>23</span>         <span>echo</span> <span>__METHOD__</span> . ' is called! ' . json_encode(<span>func_get_args</span>()) . "\n"<span>;
</span><span>24</span>         <span>return</span> <span>isset</span>(<span>$this</span>->_properties[<span>$name</span><span>]);
</span><span>25</span> <span>    }
</span><span>26</span> 
<span>27</span>     <span>public</span> <span>function</span> __unset(<span>$name</span><span>){
</span><span>28</span>         <span>echo</span> <span>__METHOD__</span> . ' is called! ' . json_encode(<span>func_get_args</span>()) . "\n"<span>;
</span><span>29</span>         <span>unset</span>(<span>$this</span>->_properties[<span>$name</span><span>]);
</span><span>30</span> <span>    }
</span><span>31</span> 
<span>32</span>     <span>public</span> <span>function</span><span> dump(){
</span><span>33</span>         <span>echo</span> "====================== DUMP START ====================\n"<span>;
</span><span>34</span>         <span>echo</span> <<<<span>STR
</span><span>35</span>     a: <span>$this</span>-><span>a
</span><span>36</span>     b: <span>$this</span>-><span>b
</span><span>37</span>     c: <span>$this</span>-><span>c
</span><span>38</span>     d: <span>$this</span>-><span>d\n
</span><span>39</span> <span>STR;
</span><span>40</span>         <span>foreach</span>(<span>$this</span>->_properties <span>as</span> <span>$k</span> => <span>$v</span><span>){
</span><span>41</span>             <span>echo</span> <<<<span>STR
</span><span>42</span>     Property <span>$k</span>: <span>$v</span><span>\n
</span><span>43</span> <span>STR;
</span><span>44</span> <span>        }
</span><span>45</span>     
<span>46</span>         <span>echo</span> "====================== DUMP STOP =====================\n"<span>;
</span><span>47</span>         
<span>48</span> <span>    }
</span><span>49</span> <span>}
</span><span>50</span> <span>$string</span> = 'abcdef'<span>;
</span><span>51</span> <span>$obj</span> = <span>new</span><span> Cls();
</span><span>52</span> 
<span>53</span> <span>$list</span> = <span>array</span>('isset', 'get', 'set', 'isset', 'unset', 'isset'<span>);
</span><span>54</span> <span>$obj</span>-><span>dump();
</span><span>55</span> <span>foreach</span>(<span>$list</span> <span>as</span> <span>$method</span><span>){
</span><span>56</span>     <span>for</span>(<span>$i</span> = 0 ; <span>$i</span> < <span>strlen</span>(<span>$string</span>) ; <span>$i</span> ++<span>){
</span><span>57</span>         <span>$char</span> = <span>$string</span>{<span>$i</span><span>};
</span><span>58</span>         <span>echo</span> "------ <span>$method</span> : <span>$char</span> ------\n"<span>;
</span><span>59</span>         <span>switch</span>(<span>$method</span><span>){
</span><span>60</span>             <span>case</span> 'isset':
<span>61</span>                 <span>echo</span> json_encode(<span>$tmp</span> = <span>isset</span>(<span>$obj</span>-><span>$char</span>)) . "\n"<span>;
</span><span>62</span>                 <span>break</span><span>;
</span><span>63</span>             <span>case</span> 'get':
<span>64</span>                 <span>echo</span> json_encode(<span>$tmp</span> = <span>$obj</span>-><span>$char</span>) . "\n"<span>;
</span><span>65</span>                 <span>break</span><span>;
</span><span>66</span>             <span>case</span> 'set':
<span>67</span>                 <span>echo</span> json_encode(<span>$tmp</span> = <span>$obj</span>-><span>$char</span> = <span>$char</span> . "-val") . "\n"<span>;
</span><span>68</span>                 <span>break</span><span>;
</span><span>69</span>             <span>case</span> 'unset':
<span>70</span>                 <span>unset</span>(<span>$obj</span>-><span>$char</span><span>);
</span><span>71</span>                 <span>break</span><span>;
</span><span>72</span>             <span>default</span>:
<span>73</span>                 <span>break</span><span>;
</span><span>74</span> <span>        }
</span><span>75</span> <span>    }
</span><span>76</span>     <span>$obj</span>-><span>dump();
</span><span>77</span> }
Copy after login

Result output:

====================== DUMP START ====================<span>
    a</span>: 0<span>
    b</span>: 1<span>
    c</span>: 2<span>
    d</span>: 3<span>
    Property </span>0: 0
====================== DUMP STOP =====================
------ <span>isset</span> : a ------<span>
Cls</span>::__isset is called! ["a"<span>]
</span><span>false</span>
------ <span>isset</span> : b ------<span>
Cls</span>::__isset is called! ["b"<span>]
</span><span>false</span>
------ <span>isset</span> : c ------
<span>true</span>
------ <span>isset</span> : d ------
<span>true</span>
------ <span>isset</span> : e ------<span>
Cls</span>::__isset is called! ["e"<span>]
</span><span>false</span>
------ <span>isset</span> : f ------<span>
Cls</span>::__isset is called! ["f"<span>]
</span><span>false</span>
====================== DUMP START ====================<span>
    a</span>: 0<span>
    b</span>: 1<span>
    c</span>: 2<span>
    d</span>: 3<span>
    Property </span>0: 0
====================== DUMP STOP =====================
------ get : a ------<span>
Cls</span>::__get is called! ["a"<span>]
</span><span>null</span>
------ get : b ------<span>
Cls</span>::__get is called! ["b"<span>]
</span><span>null</span>
------ get : c ------
2
------ get : d ------
3
------ get : e ------<span>
Cls</span>::__get is called! ["e"<span>]
</span><span>null</span>
------ get : f ------<span>
Cls</span>::__get is called! ["f"<span>]
</span><span>null</span>
====================== DUMP START ====================<span>
    a</span>: 0<span>
    b</span>: 1<span>
    c</span>: 2<span>
    d</span>: 3<span>
    Property </span>0: 0
====================== DUMP STOP =====================
------ set : a ------<span>
Cls</span>::__set is called! ["a","a-val"<span>]
</span>"a-val"
------ set : b ------<span>
Cls</span>::__set is called! ["b","b-val"<span>]
</span>"b-val"
------ set : c ------
"c-val"
------ set : d ------
"d-val"
------ set : e ------<span>
Cls</span>::__set is called! ["e","e-val"<span>]
</span>"e-val"
------ set : f ------<span>
Cls</span>::__set is called! ["f","f-val"<span>]
</span>"f-val"
====================== DUMP START ====================<span>
    a</span>: 0<span>
    b</span>: 1<span>
    c</span>: c-<span>val
    d</span>: d-<span>val
    Property </span>0: 0<span>
    Property a</span>: a-<span>val
    Property b</span>: b-<span>val
    Property e</span>: e-<span>val
    Property f</span>: f-<span>val
</span>====================== DUMP STOP =====================
------ <span>isset</span> : a ------<span>
Cls</span>::__isset is called! ["a"<span>]
</span><span>true</span>
------ <span>isset</span> : b ------<span>
Cls</span>::__isset is called! ["b"<span>]
</span><span>true</span>
------ <span>isset</span> : c ------
<span>true</span>
------ <span>isset</span> : d ------
<span>true</span>
------ <span>isset</span> : e ------<span>
Cls</span>::__isset is called! ["e"<span>]
</span><span>true</span>
------ <span>isset</span> : f ------<span>
Cls</span>::__isset is called! ["f"<span>]
</span><span>true</span>
====================== DUMP START ====================<span>
    a</span>: 0<span>
    b</span>: 1<span>
    c</span>: c-<span>val
    d</span>: d-<span>val
    Property </span>0: 0<span>
    Property a</span>: a-<span>val
    Property b</span>: b-<span>val
    Property e</span>: e-<span>val
    Property f</span>: f-<span>val
</span>====================== DUMP STOP =====================
------ <span>unset</span> : a ------<span>
Cls</span>::__unset is called! ["a"<span>]
</span>------ <span>unset</span> : b ------<span>
Cls</span>::__unset is called! ["b"<span>]
</span>------ <span>unset</span> : c ------
------ <span>unset</span> : d ------
------ <span>unset</span> : e ------<span>
Cls</span>::__unset is called! ["e"<span>]
</span>------ <span>unset</span> : f ------<span>
Cls</span>::__unset is called! ["f"<span>]
</span>====================== DUMP START ====================<span>
Cls</span>::__get is called! ["c"<span>]
Cls</span>::__get is called! ["d"<span>]
    a</span>: 0<span>
    b</span>: 1<span>
    c</span>:<span> 
    d</span>:<span> 
    Property </span>0: 0
====================== DUMP STOP =====================
------ <span>isset</span> : a ------<span>
Cls</span>::__isset is called! ["a"<span>]
</span><span>false</span>
------ <span>isset</span> : b ------<span>
Cls</span>::__isset is called! ["b"<span>]
</span><span>false</span>
------ <span>isset</span> : c ------<span>
Cls</span>::__isset is called! ["c"<span>]
</span><span>false</span>
------ <span>isset</span> : d ------<span>
Cls</span>::__isset is called! ["d"<span>]
</span><span>false</span>
------ <span>isset</span> : e ------<span>
Cls</span>::__isset is called! ["e"<span>]
</span><span>false</span>
------ <span>isset</span> : f ------<span>
Cls</span>::__isset is called! ["f"<span>]
</span><span>false</span>
====================== DUMP START ====================<span>
Cls</span>::__get is called! ["c"<span>]
Cls</span>::__get is called! ["d"<span>]
    a</span>: 0<span>
    b</span>: 1<span>
    c</span>:<span> 
    d</span>:<span> 
    Property </span>0: 0
====================== DUMP STOP =====================
Copy after login

Specially emphasize that these methods will only be triggered when this attribute does not exist (based on current access permissions). Therefore it is strongly recommended to use certain key values ​​for get/set processing, especially the corresponding key values ​​​​should not have access rights issues , such as a and b in the above example, which will lead to in the class The processing methods inside, outside the class, and within the subclass are different, resulting in unpredictable return values ​​during development, which can easily lead to bugs.

The empty method cannot call the attribute overloaded method.

<span>$tmp</span> = <span>$obj</span>-><span>$char</span> = <span>$char</span> . "-val"
Copy after login

In this example, the return value of __set itself will be ignored, and __get will not be called.

In addition: property overloaded methods must be declared public, and parameters cannot be passed by reference. Static properties cannot be overloaded through these methods, and these methods cannot be declared static.

Of course, when using magic methods, it will also affect the reflection system.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1106389.htmlTechArticlephp magic method - attribute overloading method, php magic attribute overloading PHP has a very magical method, these Methods are reserved methods and usually are not called explicitly externally, they use double...
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles