Examples of overloading and magic methods in PHP

Source: Internet
Author: User
Tags export class
definition: PHP retains all class methods starting with (two underscores) as a magic method. Therefore, in addition to the above magic method when defining a class method, it is not recommended to assume a prefix.

role : Using the Schema method can easily implement PHP object-oriented overloading (overloading, dynamic creation of class properties and methods)

In fact, many bloggers have written these methods 、、、 but I will say it again. Who let you to listen to, yards so many words also not easy to read again go!

1.construct,destruct
Constuct is called when the object is built;
Destruct explicitly destroys the object or is called at the end of the script;

Class Foo {    private $name;    Private $link;    Public function construct ($name) {        $this->name = $name;    }        Public Function destruct () {            echo ' destroying: ', $this->name, Php_eol;//php_eol represents a newline character for PHP}    }

Stop, first, Amway. The definition and use of a heavy-duty method:

definition : PHP provides an " overload " (overloading) that refers to the dynamic creation of class properties and methods. (We do this by magic methods )

Action : An overloaded method is called when a class property or method is called that is undefined or invisible under the current environment. these undefined or invisible class properties or methods are used later by using the inaccessible properties and the inaccessible methods (inaccessible methods).

Note : All overloaded methods must be declared public.

2.get, set, Isset, unset, call, callstatic//Why put it together?


Set is called when a property assignment is not accessible or does not exist
Called when get read is inaccessible or does not exist

Isset called when isset () or empty () is called on an inaccessible or nonexistent property
Unset called when an unreachable or nonexistent property is unset

Called when call calls a method that is not accessible or does not exist
Called when Callstatic calls a static method that is not accessible or does not exist

Example #1 using Get (), set (), Isset (), and unset () for property overloading

<?phpclass PropertyTest {/** The overloaded data is saved in this */private $data = Array ();     /** overloads cannot be used on properties that have already been defined */public $declared = 1;    /** The overload occurs only if this property is accessed from outside the class */private $hidden = 2;        Public function set ($name, $value) {echo ' Setting ' $name ' to ' $value ' \ n ';    $this->data[$name] = $value;        The Public function get ($name) {echo ' Getting ' $name ' \ n ';        if (Array_key_exists ($name, $this->data)) {return $this->data[$name];        } $trace = 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 after version */Public function isset ($name) {echo "is ' $name ' set?\n";    return Isset ($this->data[$name]);        }/** PHP 5.1.0 version */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->a. Var_dump (Isset ($obj->a)), unset ($obj->a), Var_dump (Isset ($obj->a)), echo "\ n", Echo $obj Declared.  "\ n"; echo "let's experiment with the private property named ' Hidden ': \ n"; echo "privates is 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";? >

Have you finished? Good looking!

5.sleep,wakeup
Sleep is called when using serialize, which is useful when you don't need to save all the data for a large object

Wakeup is called when using unserialize, and can be used for initialization of 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 when the object clone is being used to adjust the cloning behavior of the 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    $object 1;    Public $object 2;    function Clone ()    {              //forces a copy of This->object, otherwise it still points to the same object        $this->object1 = Clone $this->object1;    }} $obj = new Mycloneable (), $obj->object1 = new Subobject (), $obj->object2 = new Subobject (), $obj 2 = Clone $obj;p rint ("O Riginal object:\n ");p Rint_r ($obj);p rint (" Cloned object:\n ");p Rint_r ($obj 2);? >

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    $object 1;    Public $object 2;    function Clone ()    {              //forces a copy of This->object, otherwise it still points to the same object        $this->object1 = Clone $this->object1;    }} $obj = new Mycloneable (), $obj->object1 = new Subobject (), $obj->object2 = new Subobject (), $obj 2 = Clone $obj;p rint ("O Riginal object:\n ");p Rint_r ($obj);p rint (" Cloned object:\n ");p Rint_r ($obj 2);? >

8.set_state
This static method is called when the Var_export () export class is called. Use the return value of Set_state as the return value of Var_export.

<?phpclass a{public $var 1;    Public $var 2;        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 ' + ' fo O ',//)); Var_dump ($b);? 
Related Article

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.