search
HomeBackend DevelopmentPHP TutorialPHP magic method - attribute overloading method, PHP magic attribute overloading_PHP tutorial

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

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

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

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"

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
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

HTTP Method Verification in LaravelHTTP Method Verification in LaravelMar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

Discover File Downloads in Laravel with Storage::downloadDiscover File Downloads in Laravel with Storage::downloadMar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use