PHP 5.3 new magic method _ invoke overview, 5.3 _ invoke

Source: Internet
Author: User
Tags autoload php error php example

PHP 5.3 new magic method _ invoke overview, 5.3 _ invoke

PHP has added a magic method named _ invoke since Version 5.3. Using this method, you can directly call an object after creating an instance. Example:

class testClass{public function __invoke{print "hello world";}}$n = new testClass;$n();

The execution result is:

hello world。

Official php example:

class CallableClass{public function __invoke($x){var_dump($x);}}$obj = new CallableClass;$obj(5);var_dump(is_callable($obj));

Appendix:Other PHP magic methods:

Php classes can use magic methods. It specifies that all methods starting with two underscores (_) are retained as magic methods. Therefore, we recommend that you do not start with _ In the function name unless you want to reload the existing magic methods.

The function names _ construct, _ destruct, _ call, _ callStatic, _ get, _ set, _ isset, _ unset, _ sleep, _ wakeup, _ toString, _ invoke, _ set_state and _ clone are magical in PHP classes. you cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

The following two methods are designed for attributes that are not declared in the class and their parent class.
_ Get ($ property) When an undefined property is called, this method is triggered and the passed parameter is the name of the accessed property.
_ Set ($ property, $ value) is triggered when an undefined attribute is assigned a value. The passed parameter is the set attribute name and value.
Here, there is no declaration that the access control is "proteced" and "private" when an object is called (that is, an attribute with no access permission ).
Similar to the _ get method and _ set method, there is no declaration here, including the access control for the proteced and private attributes when the object is called (that is, the attribute with no access permission ).

The undefined method here includes methods without access permission. If the method does not exist, find this method in the parent class. If the parent class does not exist, call the _ call () method of this class () if the _ call () method does not exist in this class, find the _ call () method in the parent class.

_ Autoload FunctionIt is automatically called when trying to use a class that has not been defined. By calling this function, the script engine has the last chance to load the required class before a php error fails.

Note:The exception thrown in the _ autoload function cannot be caught by the catch statement block and cause fatal errors. Therefore, the function itself should be captured.

_ Construct ConstructorThis method is called when an object is created. The advantage of using this method relative to php4 is that the constructor has a unique name regardless of the name of the class in which it is located. in this way, you do not need to change the name of the constructor when changing the class name.

_ Destruct destructorPhp will call this method before the object is destroyed (that is, before it is cleared from the memory. By default, php only releases the memory occupied by object properties and destroys object-related resources. The Destructor allows you to execute arbitrary code after using an object to clear the memory. When php decides that your script is no longer related to objects, the Destructor will be called.

In the namespace of a function, this occurs when the function returns. 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 pointing to the object. Usually, the variable is assigned null or unset is called.

Object assignment in php5 is a reference assignment. If you want to copy an object, you need to use the clone method. When you call this method, the object will automatically call the _ clone magic method, if you need to perform some initialization operations on Object replication, You can implement them in the _ clone method.

_ Tostring MethodIt is automatically called when an object is converted into a string, for example, when an object is printed using echo.

Before php5.2.0, The __tostring method takes effect only when echo () or print () is used in combination. After php5.2.0, it can take effect in any string environment (for example, using the % s modifier through printf (), but not for non-string environment (such as using the % d modifier ). From php5.2.0, if an undefined _ tostring method object is converted to a string, an e_recoverable_error error is returned.

_ WakeupCalled during deserialization

Serialize () checks whether the class has a function named _ sleep. In this case, the function will run before any serialization. It can clear the object and should return an array containing all variable names to be serialized in the object.

The purpose of _ sleep is to close any database connection that an object may have, submit data in waiting or perform similar cleanup tasks. In addition, this function is useful if a very large object does not need to be fully stored.

PHP, on the contrary, unserialize () checks the existence of a function with the magic name _ wakeup. If yes, this function can reconstruct any resources that an object may have. _ Wakeup is used to reconstruct any database connections that may be lost during serialization and process other re-initialization tasks.
When you try to call an object by calling a function, the __invoke method is automatically called.

It works in a way similar to the _ call () magic method, __callstatic () is used to handle static method calls.

Php does enhance the definition of the _ callstatic () method. It must be public and declared as static. Similarly, the __call () magic method must be defined as public, and all other magic methods must be.


Php magic Method

In this way, it is for security, that is, the concept of object-oriented encapsulation. If Public is set directly, no object can set the value of this attribute freely, it does not pass the logic judgment of the task. In this way, it can increase security.

Explain in detail the magic methods in php5

PHP has completely re-developed the kernel for processing objects, providing more functions while improving performance. In earlier versions of php, the methods for processing objects and basic types (numbers, strings) are the same. This method has the following drawbacks: when an object is assigned to a variable or an object is passed through a parameter, the object will be completely copied. In the new version, the above operations will pass references (which can be understood as object identifiers), rather than values.
Many PHP programmers may not even notice the old object processing method. In fact, most php applications can run well. Or few changes are required.
Private and protected members
PHP5 introduces the concept of private and protected member variables. We can use it to define the visibility of class members.
Example
Protected members can be accessed by the quilt class, while private members can only be accessed by the class itself.

Code :--------------------------------------------------------------------------------

<? Php
Class MyClass {
Private $ Hello = "Hello, World! \ N ";
Protected $ Bar = "Hello, Foo! \ N ";
Protected $ Foo = "Hello, Bar! \ N ";

Function printHello (){
Print "MyClass: printHello ()". $ this-> Hello;
Print "MyClass: printHello ()". $ this-> Bar;
Print "MyClass: printHello ()". $ this-> Foo;
}
}

Class MyClass2 extends MyClass {
Protected $ Foo;

Function printHello (){
MyClass: printHello ();/* shocould print */
Print "MyClass2: printHello ()". $ this-> Hello;/* Shouldn't print out anything */
Print "MyClass2: printHello ()". $ this-> Bar;/* Shouldn't print (not declared )*/
Print "MyClass2: printHello ()". $ this-> Foo;/* shocould print */
}
}

$ Obj = new MyClass ();
Print $ obj-> Hello;/* Shouldn't print out anything */
Print $ obj-> Bar;/* Shouldn't print out anything */
Print $ obj-> Foo;/* shoshould ...... the remaining full text>

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.