PhP5 the Magic Method Learning notes

Source: Internet
Author: User
Tags inheritance object model php file

1.__construct () When instantiating an object, this method of this object is invoked first.

The code is as follows Copy Code
Class Test {function __construct () {echo "Before";}} $t = new test ();
Class Test {function __construct () {echo "Before";}} $t = new test ();

The output is:

Start

A constructor is a magic method that is invoked when an object is instantiated. It's often the first thing to do when a class is declared, but it's not necessary. He's like any other method. In any place in a class, a constructor can be declared, as well as other method-like inheritance. If we think of previous examples of inheritance from introduction to OOP, we can add construction methods to the animal class
1

The code is as follows Copy Code

Class animal{

Public Function __construct () {

$this->created = time ();

$this->logfile_handle = fopen ('/tmp/log.txt ', ' W ');

}

}

Now we create a class to inherit the animal Class-Penguin Class! Without adding any properties and methods in the Penguin class, we can declare and define that it inherits from the

The code is as follows Copy Code

Animal class, such as:
Class Penguin extends Animal {
}

$tux = new Penguin;
Echo $tux->created;

We know that the PHP5 object model and the same class name function are constructors of the class, so if we both define constructors and __construct () methods, PHP5 calls the constructor by default and does not invoke the __construct () function, so __construct () As the default constructor for a class
2.__destruct () This method is invoked when an object or object operation is terminated.
Java code

The code is as follows Copy Code
Class Test {function __destruct () {echo ' End ';}} $t = new Test ();
Class Test {function __destruct () {echo ' End ';}} $t = new Test ();

We can do things like releasing resources at the end of an object operation.

3.__get () is invoked when an attempt is made to read an attribute that does not exist.

If you try to read a property that does not exist for an object, PHP will give you an error message. If you add a __get method to a class, and we can use this function to implement various operations like reflection in Java.

The code is as follows Copy Code
Class Test {public Function __get ($key) {echo $key. "does not exist"; }} $t = new Test (); Echo $t->name; Will output: Name does not exist
Class Test {public Function __get ($key) {echo $key. "does not exist"; }} $t = new Test (); Echo $t->name; Will output: Name does not exist

Example

The code is as follows Copy Code

Class Penguin extends Animal {

Public function __construct ($id) {

$this->getpenguinfromdb ($id);

}

Public Function Getpenguinfromdb ($id) {

}

}


4.__set () is invoked when an attempt is made to write a value to a property that does not exist.

The code is as follows Copy Code

Class Test {public Function __set ($key, $value) {echo ' to '. $key. "Attached value". $value; }} $t = new Test (); $t->name = "Aninggo"; Is output: The name attached to the value Aninggo
Class Test {public Function __set ($key, $value) {echo ' to '. $key. "Attached value". $value; }} $t = new Test (); $t->name = "Aninggo"; Is output: The name attached to the value Aninggo

5.__call () This method is invoked when an attempt is made to invoke a method that does not exist for an object.

The code is as follows Copy Code


Class Test {public Function __call ($Key, $Args) {echo] the {$Key} method you are calling does not exist. The parameters you pass in are: ". Print_r ($Args, true); }} $t = new Test (); $t->getname (Aning,go);
Class Test {public Function __call ($Key, $Args) {echo] the {$Key} method you are calling does not exist. The parameters you pass in are: ". Print_r ($Args, true); }} $t = new Test (); $t->getname (Aning,go);
The program will output:


The GetName method you are calling does not exist. parameter is: Array
(
[0] => aning
[1] => Go
)
The GetName method you are calling does not exist. parameter is: Array
(
[0] => aning
[1] => Go
)

6.__tostring () is called when an object is printed

This method is similar to the Java ToString method, and when we print the object directly, the callback uses this function

The code is as follows Copy Code


Class Penguin {

Public function __construct ($name) {

$this->species = ' Penguin ';

$this->name = $name;

}

Public Function __tostring () {

Return $this->name. " (" . $this->species. ") n";

}

}

In the appropriate place, the output of the object is output by invoking Echo, such as:

The code is as follows Copy Code

$tux = new Penguin (' Tux ');

Echo $tux;


7.__clone ()

We have seen an example of using the Clone keyword, in my introduction to the second part of OOP, to create a copy of the object instead of having two variables pointing to the same actual data. Overriding this method in a class, we can observe what happens when the Clone keyword is used on an object. Although this is not something we can meet every day, a nice use case is to create a real single case pattern by adding a private access modifier to this method.

The code is as follows Copy Code

Class Test {public Function __clone () {echo "I was copied!" "; } } $t = new Test (); $t 1 = clone $t; program output: I was cloned!


__sleep

The __sleep () method is invoked when the object is serialized and allows you to handle serialization. There are all kinds of programs, a good example if an object contains a pointer of some kind, such as a file handle or referencing another object. These reference types are useless when the object is serialized and then deserialized, because the target of these types of references may no longer exist or be valid. Therefore, it is best to cancel this information before storing them.

__wakeup

__wakeup () is the opposite of the __sleep () method, allowing you to change the behavior of object deserialization. Used with __sleep (), can be used to recover deleted handles and objects when the object is serialized. A good example is that the database handle is set to be canceled when the item is serialized and then restored to the current configuration to set up the project, the solution serializes a database handle.


The __autoload () method can be

For example, we define the file of the person class above as person_class.php,
Then create a new php file test.php, edit the content:

The code is as follows Copy Code
function __autoload ($calssName)
{
Include $className. " _class.php "; You see this, maybe you get it? Ha ha
}
$p = new Person ("Mifan", 22);
$p->say ();

This will not be an error if you execute the test.php page.

PHP Magic method In general under what circumstances need to use


As a simple example, there is no attribute $name in the class; But if you accidentally access this property, you'll get an error at this point. But allow you to set Magic method __get ($name) {return $name. "does not Exist"}; __get ($name) is automatically invoked so that the program does not interrupt execution because you have accessed a non-existent attribute error
Called when __get ($v) is added to access an undefined property.
__set ($v)? Called when a property assignment is not defined,
__isset ($v) is called when the Isset () function is used for undefined properties.
__unset ($v) and Isset ($v) are similar
__call ($method) access to undefined methods is called

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.