PHP's trick function and magic constants

Source: Internet
Author: User
Tags object serialization
PHP's Magic function and Magic constants

1. __construct ()
Called when an object is instantiated, and when __construct and a function with the name of the class name are present, __construct is called and the other is not called.

2. __destruct ()
Called when an object is deleted or when an object operation terminates.
3. __call ()
The object calls a method, and if the method exists, it is called directly; if it does not exist, it will call the __call function.
4. __get ()
When a property of an object is read, the property value is returned directly if the property exists, or the __get function is called if it does not exist.
5. __set ()
When a property of an object is set, the value is assigned directly if the property exists, or the __set function is called if it does not exist.
6. __tostring ()
Called when an object is printed. such as Echo $obj; or print $obj;
7. __clone ()
Called when the object is cloned. such as: $t =new Test (); $t 1=clone $t;
8. __sleep ()
Serialize before being called. If the object is relatively large, want to cut a bit of the east and then serialize, you can consider this function.
9. __wakeup ()
Unserialize is called to do some initialization of the object.
10. __isset ()
Called when detecting whether an object's properties exist. such as: Isset ($c->name).
11. __unset ()
Called when a property of an object is unset. such as: unset ($c->name).
12. __set_state ()
Called when the Var_export is called. Use the return value of __set_state as the return value of Var_export.
13. __autoload ()
When an object is instantiated, the method is called if the corresponding class does not exist.
[Magic constant]
1. __line__
Returns the current line number in the file.

2. __file__
Returns the full path and file name of the file. If used in the include file, the include filename is returned. Since PHP 4.0.2, __file__ always contains an absolute path, and the previous version sometimes contains a relative path.
3. __function__
Returns the name of the function (PHP 4.3.0 new addition). From PHP 5 This constant returns the name (case-sensitive) when the function is defined. In PHP 4, this value is always in lowercase letters.
4. __class__
Returns the name of the class (PHP 4.3.0 new addition). From PHP 5 This constant returns the name of the class when it is defined (case-sensitive). In PHP 4, this value is always in lowercase letters.
5. __method__
Returns the method name of the class (PHP 5.0.0 new). Returns the name of the method when it is defined (case-sensitive).
(1) First knowledge of magic method
Php5.0 has provided us with a lot of object-oriented features since its release, especially for our easy-to-use magic methods that allow us to simplify our coding and better design our systems. Today we will come to know the Magic method that php5.0 offers us.
1,__construct () When an object is instantiated, this method of the 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 same class name function are the constructors of the class, so if we define both the constructor and the __construct () method, PHP5 will call the constructor by default instead of calling the same name function, so __construct () As the default constructor for a 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 be output
End
We can do things like freeing resources at the end of an object operation.
3,__get () is called when attempting to read a property 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 actions like reflection in Java.
Class Test
{
Public Function __get ($key)
{
Echo $key. "does not exist";
}
}
$t = new Test ();
Echo $t->name;
It will output:
Name does not exist

4,__set () is called when an attempt is made to write a value to a property that does not exist.
Class Test
{
Public Function __set ($key, $value) {
echo ' pair '. $key. "Attached value". $value;
}
}
$t = new Test ();
$t->name = "Aninggo";
It will output:
Value to name Aninggo

5,__call () Call this method when attempting to invoke a method that does not exist for an object.
Class Test
{
Public Function __call ($Key, $Args) {
echo "The {$Key} method you are calling 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 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 ToString method of Java, when we directly print the object callback with this function
Class Test
{
Public Function __tostring () {
Return "Print Test";
}
}
$t = new Test ();
Echo $t;

When the Echo $t is run, $t->__tostring () is called and the output
Print Test
7,__clone () is called when the object is cloned
Class Test
{
Public Function __clone () {
echo "I've been copied!" ";
}
}
$t = new Test ();
$t 1 = Clone $t;
Program output:
I've been cloned!
__sleep and __wakeup
Serialization serialize can convert variables including objects into continuous bytes data. You can either have a serialized variable in a file or transfer it over the network. Then crossdress the rows to revert to the original data. The classes that you define before you crossdress the objects of the class, PHP can successfully store the properties and methods of its objects. Sometimes you may need an object to be executed immediately after the crossdress is serialized. For this purpose, PHP will automatically look for __sleep and __wakeup methods.
When an object is serialized, PHP invokes the __sleep method (if one exists). After crossdress an object, PHP calls the __wakeup method. Both methods do not accept parameters. The __sleep method must return an array containing the properties that need to be serialized. PHP discards the values of other properties. If there is no __sleep method, PHP will save all properties.
Example 6.16 shows how to serialize an object using the __sleep and __wakeup methods. The id attribute is a temporary property that is not intended to be persisted in the object. The __sleep method guarantees that the ID attribute is not included in the serialized object. When crossdress a user object, the __wakeup method establishes the new value of the id attribute. This example is designed to be self-sustaining. In real-world development, you may find that objects that contain resources (like or data streams) require these methods
Object serialization
CODE: [Copy to Clipboard]
--------------------------------------------
Class User
{
Public $name;
public $id;
function __construct () {
Give User a unique ID is given a different ID
$this->id = Uniqid ();
}
function __sleep () {
Do not serialize This->id no serialization ID
Return (Array ("name"));
}
function __wakeup () {
Give User a unique ID
$this->id = Uniqid ();
}
}
Create object to create a
$u = new User;
$u->name = "Leon";
Serialize it serialization note the id attribute is not serialized and the value of ID is discarded
$s = serialize ($u);
Unserialize it crossdress the row ID is re-assigned
$u 2 = unserialize ($s);
$u and $u 2 have different IDs for different IDs $u and $U2
Print_r ($u);
Print_r ($u 2);
?>
__set_state and __invoke
The test code is as follows:
Class A {
public static function __set_state ($args)
{
$obj =new A ();
foreach ($args as $k = = $v) {
$obj $k = $v;
}
return $obj;
}
}

$a = new A;
$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"
}
It is concluded that the __set_state function is used to replicate an object, and can be defined in __set_state to make some changes to the copied object when copying the object. Unlike __clone, __set_state can accept parameters, and __set_state is even more powerful! Although the personal feel that this thing is not very useful = =!

And then say the __invoke:
The manual has a very conspicuous: Note:this feature is available since PHP 5.3.0.
The __invoke method is called if a script tries to call an object as a function.
The __invoke method will be called when the code tries to use the object as a function. What's the use of this feature?
Then look at the examples provided:

Class Callableclass {
function __invoke ($x) {
Var_dump ($x);
}
}
$obj =new Callableclass;
$obj (5);
Var_dump (Is_callable ($obj));
?>
Program output:
Int (5)
BOOL (TRUE)
It really used the object as a function ...
__autoload

There is a method in PHP5: __autoload (), simple is the automatic loading of classes;
When you try to use a class that is not organized by PHP, it looks for a __autoload global function. If this function is present, PHP invokes it with a parameter, which is the name of the class.
So simply test it.

First, create a file named "test_autoload.php":
<? Php
/**
* Test __autoload method
*
*/
Class Test_autoload {
Public Function __construct () {
echo "Test_autoload.";
}
}
?>
Note the class name, and then arbitrarily build a file to rewrite the __autoload () method, which is assumed to be "test.php";
<? Php
/**
* Overriding 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, some of the very cool experimental functions provided in PHP5 are
(1). Runkit_method_rename
This function can dynamically change the name of the function we call.
Class Test
{
function foo () {
return "Foo!";
}
}
Runkit_method_rename (
' Test ',//class name
' foo ',//function actually called
' Bar '//shows the function called
);
Echo Test::bar ();
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
' $num 1, $num 2 ',//parameters passed in
' Return $num 1 + $num 2; ',//code 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 function.
Class Foo {
function Example () {
return "Foo!";
}
}
Class Bar {
Empty class
}
Execute copy
Runkit_method_copy (' Bar ', ' baz ', ' Foo ', ' example ');
function after the copy is executed
Echo Bar::baz ();
(4) Runkit_method_redefine
Dynamically changing the return value of a function
This function allows us to easily implement mock tests of classes! Isn't it cool?
Class Example {
function foo () {
return "Foo!";
}
}
Create a Test object
$e = new Example ();
Output before testing the 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, see the name can be seen, the dynamic removal of 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
Bar

1/F Bardo 2011-04-18

3. __call ()
The object calls a method, and if the method exists, it is called directly; if it does not exist, it will call the __call function.
4. __get ()
When a property of an object is read, the property value is returned directly if the property exists, or the __get function is called if it does not exist.
5. __set ()
When a property of an object is set, the value is assigned directly if the property exists, or the __set function is called if it does not exist.

In fact, the native method to be accessed exists, only private, and triggers the call.

2/F Bardo 2011-04-18

6. __tostring ()
Called when an object is printed. such as Echo $obj; or print $obj;

Strval ($obj) will also trigger the call.

3/F Bardo 2011-04-18

1. __construct ()
Called when an object is instantiated, and when __construct and a function with the name of the class name are present, __construct is called and the other is not called.

7. __clone ()
Called when the object is cloned. such as: $t =new Test (); $t 1=clone $t;

13. __autoload ()
When an object is instantiated, the method is called if the corresponding class does not exist.


These three are operator triggers

One is the new operator. One is the clone operator.

4/F Bardo 2011-04-18

8. __sleep ()
Serialize before being called. If the object is relatively large, want to cut a bit of the east and then serialize, you can consider this function.
9. __wakeup ()
Unserialize is called to do some initialization of the object.

。 __sleep ()
not limited to limitations. Class with __call function, if no __sleep () cannot complete serialization.

  • 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.