PHP overload and magic methods, PHP overload magic methods

Source: Internet
Author: User

PHP overload and magic methods, PHP overload magic methods

First of all, you need to know what is the magic method of php. It is not magic. If you want to learn magic, it will be wrong!

Definition: PHP retains all class Methods Starting with _ (two underscores) as magic methods. Therefore, we recommend that you do not use the _ prefix in addition to the above magic methods when defining class methods.

Function: Using the pattern method, you can easily overload PHP object-oriented objects (Overloading is the dynamic creation of class attributes and methods)

In fact, many bloggers have already written these methods .. Who told you to listen? It's not easy to read so many characters!

1. _ construct ,__ destruct
_ Constuct is called when constructing an object;
_ Destruct is called to explicitly destroy an object or end the script;

Class Foo {private $ name; private $ link; public function _ construct ($ name) {$ this-> name = $ name;} public function _ destruct () {echo 'deststroying: ', $ this-> name, PHP_EOL; // PHP_EOL represents the php linefeed }}

 

The definition and usage of a wave of heavy load by Amway:

Definition: "Provided by PHP"Heavy Load"(Overloading) means to dynamically" CREATE "class attributes and methods. (We implemented it through magic methods)

Function: When you call an undefined or invisible class attribute or method in the current environment, the overload method is called. The following uses "inaccessible properties" and "inaccessible methods" to name these undefined or invisible class attributes or methods.

Note:: All overload methods must be declaredPublic.

 

2. _ get, _ set, _ isset, _ unset, _ call, and _ callStatic // Why are they put together?


_ Set is called when an inaccessible or non-existent attribute is assigned a value.
_ Get is called when reading an inaccessible or non-existent attribute

_ Isset is called when isset () or empty () is called for inaccessible or non-existent attributes
_ Unset is called when an unset operation is performed on an inaccessible or non-existent attribute.

_ Call is called when a method that is inaccessible or does not exist
_ CallStatic is called when a static method that is inaccessible or does not exist

 

Example #1 use _ get () ,__ set () ,__ isset () and _ unset () for Attribute Overloading

<? Phpclass PropertyTest {/** the overloaded data is stored here */private $ data = array (); /** the overload cannot be used in the defined attribute */public $ declared = 1;/** only when this attribute is accessed from outside the class, */private $ hidden = 2; public function _ set ($ name, $ value) {echo "Setting '$ name' to' $ value' \ n"; $ this-> data [$ name] = $ value;} public function _ get ($ name) {echo "Getting '$ name' \ n"; if (array_key_exists ($ name, $ this-> data) {return $ this-> data [$ name];} $ tr Ace = debug_backtrace (); trigger_error ('undefined property via _ get ():'. $ name. 'in '. $ trace [0] ['file']. 'on line '. $ trace [0] ['line'], E_USER_NOTICE); return null;}/** PHP 5.1.0 or later */public function _ isset ($ name) {echo "Is '$ name' set? \ N "; return isset ($ this-> data [$ name]);}/** PHP 5.1.0 or later */public function _ unset ($ name) {echo "Unsetting '$ name' \ n"; unset ($ this-> data [$ name]);}/** non-magic Method */public function getHidden () {return $ this-> hidden ;}} echo "<pre> \ n"; $ obj = new PropertyTest; $ obj-> a = 1; echo $ obj->. "\ n"; var_dump (isset ($ obj-> a); unset ($ obj-> a); var_dump (isset ($ obj-> )); echo "\ n"; echo $ obj-> declared. "\ n"; echo "Let's experiment with the private property named 'den den ': \ n"; echo "Privates are visible inside the class, so _ get () not used... \ n "; echo $ obj-> getHidden (). "\ n"; echo "Privates not visible outside of class, so _ get () is used... \ n "; echo $ obj-> hidden. "\ n";?>

Are you finished? Nice looking!


5. _ sleep ,__ wakeup
_ Sleep is called when serialize is used. It is useful when you do not need to save all data of large objects.

_ Wakeup is called when unserialize is used. It can be used to initialize objects.

<?phpclass Connection {    protected $link;    private $server, $username, $password, $db;        public function __construct($server, $username, $password, $db)    {        $this->server = $server;        $this->username = $username;        $this->password = $password;        $this->db = $db;        $this->connect();    }        private function connect()    {        $this->link = mysql_connect($this->server, $this->username, $this->password);        mysql_select_db($this->db, $this->link);    }        public function __sleep()    {        return array('server', 'username', 'password', 'db');    }        public function __wakeup()    {        $this->connect();    }}?>

 


6. _ clone
Called to adjust the cloning behavior of an object.

<? Phpclass SubObject {static $ instances = 0; public $ instance; public function _ construct () {$ this-> instance = ++ self: $ instances ;} public function _ clone () {$ this-> instance = + self: $ instances;} class MyCloneable {public $ object1; public $ object2; function _ clone () {// force copy this-> object; otherwise, it still points to the same object $ this-> object1 = clone $ this-> object1 ;}} $ obj = new MyCloneable (); $ obj-> object1 = new SubOb Ject (); $ obj-> object2 = new SubObject (); $ obj2 = clone $ obj; print ("Original Object: \ n"); print_r ($ obj ); print ("Cloned Object: \ n"); print_r ($ obj2);?>

 


7. _ toString
Called when a class is converted to a string

<? Phpclass SubObject {static $ instances = 0; public $ instance; public function _ construct () {$ this-> instance = ++ self: $ instances ;} public function _ clone () {$ this-> instance = + self: $ instances;} class MyCloneable {public $ object1; public $ object2; function _ clone () {// force copy this-> object; otherwise, it still points to the same object $ this-> object1 = clone $ this-> object1 ;}} $ obj = new MyCloneable (); $ obj-> object1 = new SubOb Ject (); $ obj-> object2 = new SubObject (); $ obj2 = clone $ obj; print ("Original Object: \ n"); print_r ($ obj ); print ("Cloned Object: \ n"); print_r ($ obj2);?>

 

8. _ set_state
This static method is called when var_export () is called to export the class. Use the return value of _ set_state as the return value of var_export.

<?phpclass A{    public $var1;    public $var2;    public static function __set_state($an_array) // As of PHP 5.1.0    {        $obj = new A;        $obj->var1 = $an_array['var1'];        $obj->var2 = $an_array['var2'];        return $obj;    }}$a = new A;$a->var1 = 5;$a->var2 = 'foo';eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(                                            //    'var1' => 5,                                            //    'var2' => 'foo',                                            // ));var_dump($b);?>

 

Enmmm, I know you can't remember it .. Who can remember this? It's so annoying. Well, come on, it's not over yet. For more information, please refer to the official PHP documentation: http://php.net/manual/zh/. don't beat me. If you want to see it, you can enjoy it! In addition, you 'd better run the code in the compiler. Otherwise, after reading the code, you probably didn't see a 2333 error ····

Original Author, reprinted please indicate the source

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.