Those years we missed the Magic method (Magic Methods) _php Tips

Source: Internet
Author: User
Tags export class mixed modifier php error

One advantage of PHP objects is that you can use magic methods that override the default behavior of a class without having to modify the external code, which makes the PHP syntax less redundant and more extensible. These methods are well identified and they all start with a double underline (__).
For example: __construct (), __destruct (), __call (), __callstatic (), __get (), __set (), __isset (), __unset (), __sleep (), __wakeup () , __tostring (), __invoke (), __set_state (), and __clone () are called "Magic Methods" (Magic methods) in PHP. You cannot use these method names when naming your own class methods, unless you want to use their magic features.

Attention:

PHP preserves all class methods that begin with __ (two underscores) as magic methods. Therefore, in addition to the above magic method, it is recommended that you do not prefix the class method with __.

1, __get, __set

The two methods are designed for properties that are not declared in the class and their parent classes.

Copy Code code as follows:

__get (string $name)//This method is accessed when an undefined property is invoked;
__set (String $name, mixed $value)//is invoked when assigning a value to an undefined property;

The absence of a declaration here includes a property (that is, a property that has no access) when an object invocation is used, and the access control is proteced,private.

2, __isset, __unset

Copy Code code as follows:

__isset ($property)//This method is called when the Isset () function is invoked on an undefined property;
__unset ($property)//This method is called when the unset () function is invoked on an undefined property;

3, __call, __callstatic

Copy Code code as follows:
__call (string $name, array $arguments)//When an undefined method is invoked, this method is called.

Undefined methods here include methods that do not have permission access.

Copy Code code as follows:
__callstatic (string $name, array $arguments)

When an inaccessible method is invoked in a static method, such as undefined or invisible, __callstatic () is invoked.

__callstatic It works like the __call () Magic Method, __callstatic () is to handle static method calls, PHP5.3.0 the above version is valid.
PHP does strengthen the definition of the __callstatic () method, it must be public and must be declared static. Similarly, the __call () Magic method must be defined as public, and all other magic methods must be so.

4, __autoload

The __autoload function, which is invoked automatically when an attempt is made to use a class that has not been defined. By calling this function, the script engine had the last chance to load the class that was required before the PHP error failed.
Note: Exceptions thrown in the __autoload function cannot be caught by a catch statement block and cause a fatal error.


5, __construct, __destruct

__construct constructs a method that is called when an object is created.
The advantage of using this method is that you can make the construction method have a unique name, regardless of the name of the class in which it resides. So you don't need to change the name of the constructor when you change the name of the class.
__destruct destructor, PHP calls this method before the object is destroyed (that is, before it is purged from memory).
By default, PHP only frees the memory occupied by object properties and destroys object-related resources.
Destructors allow you to clean up memory by executing arbitrary code after using an object.
Destructors are invoked when PHP determines that your script is no longer related to objects.
Within the namespace of a function, this occurs when the function return.
For global variables, this occurs at the end of the script. If you want to explicitly destroy an object, you can assign any other value to the variable that points to the object, usually assigning the variable on duty to null or calling unset.

6, __clone

An object assignment in PHP5 is a reference assignment that is used, and if you want to copy an object, you need to use the Clone method, which is called by the object to invoke the __clone magic method automatically.
If you need to perform some initialization operations on object replication, you can implement it in the __clone method.

7, __tostring

Copy Code code as follows:

public string __tostring (void)

The __tostring method is invoked automatically when an object is converted to a string, such as when the object is printed with Echo. What should be shown. This method must return a string, or it will emit a fatal error at the e_recoverable_error level.

Copy Code code as follows:

$myObject = new MyClass ();
Echo $myObject;
'll look for a magic method echo
$myObject->__tostring ();

Note: You cannot throw an exception in the __tostring () method. Doing so can lead to fatal errors.

It should be noted that before PHP 5.2.0, the __tostring () method takes effect only when used directly with Echo or print. After PHP 5.2.0, it can take effect in any string environment (for example, by printf (), using the%s modifier) but not in a non-string environment (such as using the%d modifier). From PHP 5.2.0, if you convert an object that does not define a __tostring () method to a string, a E_recoverable_error level error is generated.

8, __sleep () and __wakeup ()

Copy Code code as follows:

Public array __sleep (void)
void __wakeup (void)

The serialize () function checks whether a magic method __sleep () exists in the class. If present, the method is invoked before the serialization operation is performed. This feature can be used to clean up objects and return an array containing all the names of the variables that should be serialized in the object. If the method does not return any content, NULL is serialized and a E_notice level error is generated.

Attention:

__sleep () cannot return the name of the private member of the parent class, which results in a e_notice level error. You can use the Serializable interface instead.
The __sleep () method is often used to submit uncommitted data, or similar cleanup operations. At the same time, if there are some large objects, but do not need to save all, this function is very useful.
Conversely, unserialize () checks for the existence of a __wakeup () method. If present, the __wakeup method is called first, and the resource required by the object is prepared beforehand.
__wakeup () is often used in deserialization operations, such as the re-establishing a database connection, or performing other initialization operations.

9, __invoke ()

Copy Code code as follows:
Mixed __invoke ([$ ...])

The __invoke () method is invoked automatically when an attempt is made to call an object in the form of a calling function.

10, __set_state ()

Copy Code code as follows:
Static object __set_state (array $properties)

This static method is invoked when the Var_export () export class is invoked from PHP 5.1.0.
The unique parameter of this method is an array that contains class attributes arranged by array (' property ' => value, ...).

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.