Magic methods and automatic loading of classes in PHP class

Source: Internet
Author: User
Tags autoload php class
    1. Class Connection {
    2. protected $link;
    3. Private $server, $username, $password, $db;
    4. Public function __construct ($server, $username, $password, $db) {
    5. $this->server = $server;
    6. $this->username = $username;
    7. $this->password = $password;
    8. $this->db = $db;
    9. $this->connect ();
    10. }
    11. Private Function Connect () {
    12. $this->link = mysql_connect ($this->server, $this->username, $this->password);
    13. mysql_select_db ($this->db, $this->link);
    14. }
    15. Public Function __sleep () {//serialization only need to save values for these properties
    16. Return array (' Server ', ' username ', ' password ', ' db ');//must return an array
    17. }
    18. Public Function __wakeup () {//deserialize the database immediately after getting the object
    19. $this->connect ();
    20. }
    21. }
Copy Code

__tostring (): Called when attempting to use an object as a string, returns a string like the JS object's toString ()

__invoke (): Called when an object is called as a function. such as $object ($a, $b) will be called $object->__invoke ($a, $b)

__set_state (): Called when an object is used with Var_export (), its return value will be printed

__clone (): Called when using a clone operation on an object, with no return value, which can be used to modify its properties before returning the object that was obtained by clone so that the object obtained by clone can be different from the property value of the object being manipulated, but it cannot be prevented by returning NULL or FALSE Object cloning operation, the object obtained by the clone operation is not returned by the return value of the method.

Note: The __get, __set method is commonly used to flexibly handle object private properties and to protect access to properties. Because the PHP object's method uses Isset () or empty () to determine the method is not considered an accessible property (write more JavaScript to note that the PHP property is the property method is not confusing) when using __get, you may be in the method When using Isset ($this->key) for attributes, especially when dealing with private properties, it is important to note that __set () has no definition and how it is defined to avoid a miscarriage of judgment. If the method of an object does not need to be passed at the time of invocation, or if the argument is fixed, the method can be attributed by the __get () method, and the method is automatically called in __get () and the value is returned.

For example, defining the __get method within a class is as follows:

    1. Public Function __get ($key) {

    2. if (Property_exists ($this, $key)) {
    3. return $this $key; Private, protected properties allow access
    4. }else if (method_exists ($this, ' get '. $key)) {
    5. return $this->{' get '. $key} ();
    6. Or....
    7. $methodName = ' get '. $key;
    8. return $this $methodName ();
    9. }else{
    10. Thrown new Exception (' class '. __class__ ' do not have property '. $key);
    11. }
    12. }

    13. Method-Attributed Access:

    14. $obj->getmodelname ();
    15. $obj->modelname; Attributed

Copy Code

Unserialize () Method: When attempting to deserialize an object, the function needs to know the class of the object, if the serialized string is derived from another way, the script environment does not have a class defining the object, you need to introduce the class file, Unserialize () the second parameter is optional The callback parameter, which is used to introduce the file where the class resides. function Importclass ($calssName) {include (' xxxx.php ');//file containing the class}unserialize ($objstr, $callbackName);

Automatic loading of classes: __autoload ()

__autoload () is a method of a function in the PHP execution environment rather than a class, and if a class is not loaded into the current file before it is used, the __autoload () function is automatically called to load the class, and usually the load rules for these classes are agreed upon. For example, these classes are included in a file named after the class name, which implements on-demand loading of the class, avoids loading unnecessary classes before the script executes, and reduces resource consumption and submission performance.

Note: Errors within __autoload () cannot be captured by Try-catch.

    1. function __autoload ($class _name) {
    2. Require_once (PATH. ' /calsses/'. $class _name. php ');
    3. }
    4. $obj 1 = new Mycalss1 ();
Copy Code

Register __autoload () function called automatically: SPL code library automatically enables Spl_autoload_register ([callback]) after PHP5.0; You can use this function to register a callback function without writing the implementation-specific load code within __autoload ().

If you use a method of a class as a callback function, you need to pass in an array: Spl_autoload_register (Array (' class_name ' | $obj, ' method_name '));

For example: Spl_autoload_register (Array ($this, ' Autoloadclass ')), Spl_autoload_register (Array (' yiibase ', ' autoload '));// The implementation of the automatic loading class of YII framework, the Yiibase class implements a AutoLoad method. Spl_autoload_register () can register multiple load functions and try all registered load functions individually before loading the class file successfully. This is useful when different classes use different logic to import class files. Spl_autoload_unregister (); Cancels a registered load function with the same parameters as Spl_autoload_register (). Spl_autoload_functions ();//returns all registered __autoload () functions in an array form

Spl_autoload (Class_name[,file_extentions]); The default implementation of the __autoload () function. Spl_autoload_register () is called when the function name is not passed in, the function is used by default, the execution rule of the function is: the class name to lowercase as the file name, the incoming file_extentions (multiple extensions are separated by commas, the default is. Inc and. PHP) is an extension that attempts to search within the include paths set in php.ini based on the resulting file name.

Spl_autoload_call (class_name);//manually invoke all registered __autoload () functions to actively load the class file Spl_autoload_extentions ([file_extentions]); Registers or returns the file name extension that can be used in spl_autoload (), which can be in the form of. A.B, for example: Spl_autoload_extentions (". class.php"); Spl_autoload_ Register (); Use Spl_autoload () to try to load the class file automatically//such spl_autoload (' myClassName '); Will attempt to load the file "myclassName.class.php".

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