Php magic functions and magic constants

Source: Internet
Author: User
Tags object serialization
Php magic function and magic constant 1. _ Construct () is called when an object is instantiated. When _ construct and a function with the same class name exist at the same time, __construct is called, and the other is not called. 2. _ Destruct () when deleting an object or an object operation is terminated, php magic functions and magic constants

1. _ Construct ()
An object is called when it is instantiated. When _ construct and a function with the class name coexist, __construct will be called, and the other will not be called.

2. _ Destruct ()
It is called when an object or object operation is terminated.
3. _ Call ()
An object calls a method. if a method exists, it is called directly. if the method does not exist, the _ call function is called.
4. _ Get ()
When reading an object property, if the property exists, the property value is directly returned. if the property does not exist, the _ get function is called.
5. _ Set ()
If an object property exists, the value is assigned directly. if the property does not exist, the _ set function is called.
6. _ ToString ()
It is called to print an object. Such as echo $ obj; or print $ obj;
7. _ Clone ()
Called when cloning an object. For example: $ t = new Test (); $ t1 = clone $ t;
8. _ Sleep ()
Serialize is called before. If the object is large and you want to delete something and serialize it, consider this function.
9. _ Wakeup ()
Unserialize is called to initialize objects.
10. _ Isset ()
It is called to check whether an object property exists. For example, isset ($ c-> name ).
11. _ Unset ()
Unset an object property is called. For example, unset ($ c-> name ).
12. _ Set_state ()
Called when var_export is called. Use the return value of _ set_state as the return value of var_export.
13. _ Autoload ()
When instantiating an object, if the corresponding class does not exist, this method is called.
[Magic constant]
1. _ LINE __
Returns the current row number in the file.

2. _ FILE __
Returns the complete file path and file name. If it is used in a include file, the include file name is returned. Starting from PHP 4.0.2, __file _ always contains an absolute path, while earlier versions sometimes contain a relative path.
3. _ FUNCTION __
Returns the function name (new in PHP 4.3.0 ). Starting from PHP 5, this constant returns the name (case sensitive) when the function is defined ). In PHP 4, the value is always lowercase letters.
4. _ CLASS __
The name of the returned class (new in PHP 4.3.0 ). Starting from PHP 5, this constant returns the name (case sensitive) when the class is defined ). In PHP 4, the value is always lowercase letters.
5. _ METHOD __
Method name of the returned class (new PHP 5.0.0 ). Returns the name (case sensitive) when the method is defined ).
(1) first knowledge of magic methods
Since the release of Php5.0, many object-oriented features have been provided for us, especially a lot of easy-to-use magic methods. these magic methods allow us to simplify our coding, better design our system. Today, let's get to know the magic methods provided by php5.0.
1 ,__ construct () when instantiating an object, this method of this object is called first.

Class Test
{
Function _ construct (){
Echo "before ";
}
}
$ T = new Test ();

The output is:
Start

Class Test
{
Function Test (){
Echo "end2 ";
}
Function _ construct (){
Echo "end ";
}
}
$ T = new Test ();
// Output end
?>
We know that the php5 object model and the function with the same class name are class constructor. if we define the constructor and The _ construct () method at the same time, php5 calls constructor by default instead of similar name functions, so _ construct () is the default constructor of the class.
2 ,__ destruct () this method is called when an object or object operation is terminated.

Class Test
{
Function _ destruct (){
Echo "end ";
}
}
$ T = new Test ();
Will output
End
We can release resources at the end of the object operation.
3 ,__ get () is called when an attempt is made to read an attribute that does not exist.
If you try to read an attribute that does not exist in an object, PHP will give an error message. If the _ get method is added to the class, and we can use this function to implement operations similar to reflection in java.
Class Test
{
Public function _ get ($ key)
{
Echo $ key. "nonexistent ";
}
}
$ T = new Test ();
Echo $ t-> name;
The output is as follows:
Name does not exist

4 ,__ set () is called when you try to write a value to an attribute that does not exist.
Class Test
{
Public function _ set ($ key, $ value ){
Echo 'to'. $ key. "value". $ value;
}
}
$ T = new Test ();
$ T-> name = "aninggo ";
The output is as follows:
Name value aninggo

5 ,__ call () this method is called when you try to call a method that does not exist in an object.
Class Test
{
Public function _ call ($ Key, $ Args ){
Echo "the {$ Key} method you want to call does not exist. The parameter you passed in is: ". print_r ($ Args, true );
}
}
$ T = new Test ();
$ T-> getName (aning, go );
The program will output:
The getName method you want to call does not exist. The parameter is Array.
(
[0] => aning
[1] => go
)
6 ,__ toString () is called when an object is printed
This method is similar to the toString method of java. We call this function when we print the object directly.
Class Test
{
Public function _ toString (){
Return "print Test ";
}
}
$ T = new Test ();
Echo $ t;

When echo $ t; is run, $ t->__ toString () is called to output
Print Test
7 ,__ clone () is called when the object is cloned
Class Test
{
Public function _ clone (){
Echo "I have been copied! ";
}
}
$ T = new Test ();
$ T1 = clone $ t;
Program output:
I have been cloned!
_ Sleep and _ wakeup
Serialize can include objects and convert them into continuous bytes data. you can save serialized variables in a file or transmit them over the network. then, the data is deserialized and restored to the original data. PHP can successfully store the attributes and methods of the objects defined before the objects of the deserialization class. sometimes you may need an object to be executed immediately after deserialization. for this purpose, PHP will automatically find the _ sleep and _ wakeup methods.
When an object is serialized, PHP calls the _ sleep method (if any ). after an object is deserialized, PHP calls the _ wakeup method. both methods do not accept parameters. the _ sleep method must return an array containing the attributes to be serialized. PHP will discard other attribute values. if the _ sleep method is not available, PHP will save all attributes.
Example 6.16 shows how to serialize an object using the _ sleep and _ wakeup methods. the Id attribute is a temporary attribute not intended to be retained in the object. the _ sleep method ensures that the id attribute is not included in the serialized object. when a User object is deserialized, the __wakeup method creates a new value for the id attribute. this example is designed to be self-sustaining. in actual development, you may find that objects containing resources (such as or data streams) need these methods.
Object serialization
CODE: [Copy to clipboard]
--------------------------------------------
Class User
{
Public $ name;
Public $ id;
Function _ construct (){
// Assign a different ID to the give user a unique ID
$ This-> id = uniqid ();
}
Function _ sleep (){
// Do not serialize this-> id is not serialized id
Return (array ("name "));
}
Function _ wakeup (){
// Give user a unique ID
$ This-> id = uniqid ();
}
}
// Create object creates an object
$ U = new User;
$ U-> name = "Leon ";
// Serialize it serializization note that the id attribute is not serialized, and the id value is discarded
$ S = serialize ($ u );
// Unserialize it deserialization id is re-assigned
$ U2 = unserialize ($ s );
// $ U and $ u2 have different IDs $ u and $ u2 have different IDs
Print_r ($ u );
Print_r ($ u2 );
?>
_ Set_state and _ invoke
The test code is as follows:
Class {
Public static function _ set_state ($ args)
{
$ Obj = new ();
Foreach ($ args as $ k =>v v ){
$ Obj-> $ k = $ v;
}
Return $ obj;
}
}

$ A = new;
$ A-> name = 'cluries ';
$ A-> sex = 'female ';
Eval ('$ B ='. var_export ($ a, true ).';');
Print_r ($ B );
?>
Program output
Object (A) #2 (2 ){
["Name"] => string (7) "cluries"
["Sex"] => string (6) "female"
}
Draw the following conclusion: __set_state is used to copy an object, and it can be defined in _ set_state to make some changes to the copied object during object copying. Unlike _ clone, _ set_state can accept parameters, __set_state is more powerful! Although I personally think this is not very useful =!

Then let's talk about _ invoke:
Note: This feature is available since PHP 5.3.0.
The _ invoke method is called when a script tries to call an object as a function.
_ Will the invoke method be called when the code tries to use the object as a function? A little strange. what is the use of this function?
Next, let's look at the provided example:

Class CallableClass {
Function _ invoke ($ x ){
Var_dump ($ x );
}
}
$ Obj = new CallableClass;
$ Obj (5 );
Var_dump (is_callable ($ obj ));
?>
Program output:
Int (5)
Bool (true)
Actually, the object is used as a function...
_ Autoload

In PHP5, there is a method: _ autoload (). In short, it is the automatic loading of classes;
When you try to use a class that is not organized by PHP, it will look for a global function of _ autoload. if this function exists, PHP uses a parameter to call it. the parameter is the name of the class.
Let's perform a simple test.

First, create a file named "Test_autoload.php:
<? Php
/**
* Test the _ autoload method.
*
*/
Class Test_autoload {
Public function _ construct (){
Echo "Test_autoload .";
}
}
?>
Pay attention to the class name, and create a file to rewrite the _ autoload () method. Here we assume it is "test. php ";
<? Php
/**
* Rewrite the _ autoload method
*/
Function _ autoload ($ class ){
Include $ class. '. php ';
}
$ Test = new Test_autoload ();
Unset ($ test );
?>
The final result is: Test_autoload.
------------------------------------------------
8. By the way, we will introduce several COOl experimental functions provided by php5.
(1 ). Runkit_method_rename
This function dynamically changes the name of the called function.
Class Test
{
Function foo (){
Return "foo! ";
}
}
Runkit_method_rename (
'Test', // class name
'Foo', // actually called function
'Bar' // display the called function
);
Echo Test: bar ();
The program will output
Foo!
(2) runkit_method_add
This function can dynamically add functions to the class.
Class Test
{
Function foo (){
Return "foo! ";
}
}
Runkit_method_add (
Test, // class name
'Add', // New function name
'$ Num1, $ num2', // input parameters
'Return $ num1 + $ num2; ', // code to be executed
RUNKIT_ACC_PUBLIC
);
// Call
Echo $ e-> add (12, 4 );
(3) runkit_method_copy
You can copy the functions in Class A to Class B and rename the functions.
Class Foo {
Function example (){
Return "foo! ";
}
}
Class Bar {
// Empty class
}
// Execute copy
Runkit_method_copy ('bar', 'Baz', 'foo', 'example ');
// Execute the copied function
Echo Bar: baz ();
(4) runkit_method_redefine
Dynamically modify the return value of a function
This function allows us to easily implement MOCK testing for classes! Is it COOL?
Class Example {
Function foo (){
Return "foo! ";
}
}
// Create a test object
$ E = new Example ();
// Output before the test object
Echo "Before:". $ e-> foo ();
// Modify the return value
Runkit_method_redefine (
'Example ',
'Foo ',
'',
'Return "bar! ";',
RUNKIT_ACC_PUBLIC
);
// Execution output
Echo "After:". $ e-> foo ();

(5) runkit_method_remove
This function is very simple. you can see it by name and dynamically remove the function from the class.
Class Test {
Function foo (){
Return "foo! ";
}
Function bar (){
Return "bar! ";
}
}
// Remove the foo function
Runkit_method_remove (
'Test ',
'Foo'
);
Echo implode ('', get_class_methods ('test '));
Program output
Bardo on the first floor of bar. _ Call ()
An object calls a method. if a method exists, it is called directly. if the method does not exist, the _ call function is called.
4. _ Get ()
When reading an object property, if the property exists, the property value is directly returned. if the property does not exist, the _ get function is called.
5. _ Set ()
If an object property exists, the value is assigned directly. if the property does not exist, the _ set function is called.

In fact, all native methods to be accessed exist, but they are private and will also trigger calls. Bardo on the second floor. _ ToString ()
It is called to print an object. Such as echo $ obj; or print $ obj;

Strval ($ obj) also triggers the call. Bardo on the third floor. _ Construct ()
An object is called when it is instantiated. When _ construct and a function with the class name coexist, __construct will be called, and the other will not be called.

7. _ Clone ()
Called when cloning an object. For example: $ t = new Test (); $ t1 = clone $ t;

13. _ Autoload ()
When instantiating an object, if the corresponding class does not exist, this method is called.


These three are triggered by operators.

One is the new operator. One is the clone operator. 4 floor bardo. _ Sleep ()
Serialize is called before. If the object is large and you want to delete something and serialize it, consider this function.
9. _ Wakeup ()
Unserialize is called to initialize objects.

. _ Sleep ()
It is not limited to delete. Classes with _ call functions cannot be serialized without _ sleep.

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.