Php Magic Method and Magic variable summary

Source: Internet
Author: User
Tags mixed

From the later version of PHP5, the class will be able to use the Magic method . PHP rules to start with two underscore methods are preserved as a magic method, so we recommend that the function name is best not to start, unless it is to reload the existing magic method.

There are currently some magic methods available in PHP

__construct,__destruct,__call,__get,__set,__isset,__unset,__sleep,__wakeup,__tostring,__set_state and __clone.

__construct and __destruct

__construct and __destruct are class constructors and destructors , which we often use, and I believe we are all familiar with it.

__sleep and __wakeup

__sleep and __wakeup are called when serializing a class . When serializing an object, PHP will attempt to call the object's member function __sleep () before the sequence action, and __wakeup () will be called when the object is restored using Unserialize ().

__tostring

__tostring is the value that must be returned when the object is converted to a string: return xxx; otherwise an error , such as

<?phpClassSTR {Private $str; public function __construct $str) {  $this->str =  $str;} public function __tostring () {return  $this->str;} }  $class = new Str ( ' Hello '); echo  $class; //here the object is converted to string, so the __tostring ?>    is called  

The example above will output the Hello

__set_state

__set_state is called when the class is exported with Var_export () , the Magic function has only one parameter, which is an array that specifies the properties to be obtained when exporting. Rarely used in general.

__call, __get and __set

The three magic methods of __call, __get and __set are most commonly used , and __call are called when methods that do not exist in the class are called, while __get and __set are called when accessing and setting member variables that do not exist in the class.
The three function prototypes are as follows:

mixed __call(string $name, array $arguments)  void __set(string $name, mixed $value) mixed __get(string $name) 
    • 1

Examples of __call:

<?php  class  Caller { public function __call( $method , $args ) { echo "Method $method called:/n" ; print_r($args ); } } $foo = new Caller(); $foo ->test(1, 2); ?> 

The example above will output:
Method Test called:
Array
(
[0] = 1
[1] = 2
)

Examples of __get and __set:

<?phpClassAPublic$c =0;Public$arr =Array ();Publicfunction__set($k,$V) {Echo$k."/n";Echo$v."/n";$this->arr[$K] =$v; }public function __get($k) { echo ' The value of $k is '. $this->arr[$k];}} $a = new A; $a->b = 1; //Member variable B does not exist, so it calls __set $a->c = 2; the//member variable C is present, so __set is not called, no output $d = $a->b; //Member variable B does not exist, so it calls __get ?>              

The example above will output:
B
1
The value of B is 1

__isset and __unset

The two __isset and __unset are similar in principle to __get and __set, and their prototypes are as follows:

bool __isset(string $name)  void __unset(string $name) 
    • 1

As an example:

<?phpClassAPublic$c =3;Public$arr =Array (' A ' + =1,' B ' + =2);Publicfunction__isset($K) {ReturnIsset$this->arr[$k]); }Publicfunction __unset ( $k) {unset ($ This->arr[ $k]); }}  $a = new A; Var_dump (isset ( Span class= "hljs-variable" > $a->a)); //member variable A does not exist, so call __isset, return True Var_dump (isset ( $a->c)); //member variable c is present, no call to __isset, same return true unset ( $a->b); //member variable B does not exist, call __unset var_dump ( $a); ?>             
    • 1

The example above will output:

bool(true)bool(true)object(a)#1 (2) { ["c"]=>int(3) ["arr"]=>array(1) { ["a"]=>int(1) }}
__clone

Class copy (clone), if there is a definition __clone this magic method will call it.

Examples are as follows:

<?php class a {public function __clone () {echo  "Object cloned";}}  $a = new A;  $b =  $a; //$b just A $ A reference, not a clone, so do not call __clone, no output.  $c = clone  $a; //called __clone, will output object cloned ?>      
    • 1 The above example will output:

Object cloned

Reference: http://php.net/manual/zh/language.oop5.magic.php

The Magic constants of PHP

Definition: Constants with two _ starts and ends for magic constants
Note: Magic constants are case insensitive

<?php$file1 = __FILE__;$file2 = __file__;var_dump($file1);var_dump($file2);?>

The result is:
String ("F:\Apache\www\temp\php_demo\temp.php")
String ("F:\Apache\www\temp\php_demo\temp.php")

_line_

The current line number in the file.

_file_

The full path and file name of the file. If used in the included file, returns the file name that is included. From PHP 4.0.2,FILE always contains an absolute path (if it is a symbolic connection, the resolved absolute path), and the previous version sometimes contains a relative path.

_dir_

The directory where the file resides. If used in the included file, returns the directory where the included files are located. It is equivalent to DirName (FILE). Unless it is a root directory, the name in the directory does not include the trailing slash. (New in PHP 5.3.0)

_function_

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.

_class_

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. The class name includes its declared action area (for example, Foo\bar). Note that since PHP 5.4, CLASS has also worked for trait. When used in the trait method, class is the name of the classes that call the trait method.

_namespace_

The name of the current namespace (case-sensitive). This constant is defined at compile time (PHP 5.3.0 is new).

_trait_

Trait's name (PHP 5.4.0 new Plus). From PHP 5.4 This constant returns the name of the trait when it is defined (case-sensitive). The Trait name includes its declared function area (for example, Foo\bar).

_method_

The method name of the class (PHP 5.0.0 new addition). Returns the name of the method when it is defined (case-sensitive).

Php Magic Method and Magic variable summary

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.