Explain the use of Php Magic Method (Magic methods) _php Skills

Source: Internet
Author: User
Tags export class

PHP is called the Magic method by using the two-underlined method, which plays an important role in PHP. Magic methods include:

  • __construct (), constructor for class
  • __destruct (), Destructor of class
  • __call () Called when an inaccessible method is invoked in an object
  • __callstatic (), called when an inaccessible method is invoked in a static manner
  • __get (), which is called when a member variable of a class is obtained
  • __set (), which is called when a member variable of a class is set
  • __isset () Called when isset () or empty () is invoked on an inaccessible property.
  • __unset () Called when unset () is invoked on an inaccessible property.
  • __sleep (), when executing serialize (), this function is called first
  • __wakeup (), when executing unserialize (), this function is called first
  • __tostring (), the response method when a class is treated as a string
  • __invoke () The response method when calling an object in the way that a function is called
  • __set_state (), this static method is invoked when you call the Var_export () export class.
  • __clone () Called when the object copy completes

__construct () and __destruct ()

Constructors and destructors should not be unfamiliar, they are invoked when objects are created and extinct. For example, we need to open a file, open when the object is created, close when the object dies

<?php 
class Fileread
{
 protected $handle = NULL;

 function __construct () {
  $this->handle = fopen (...);
 }

 function __destruct () {
  fclose ($this->handle);
 }
? >

These two methods can be extended when inheriting, for example:

<?php 
class Tmpfileread extends Fileread
{
 function __construct () {
  parent::__construct ();
 }

 function __destruct () {
  parent::__destruct ()}
}
? >

__call () and __callstatic ()

Both methods are called when an inaccessible method is invoked in an object, which is a static method. These two methods may be used in the variable method (Variable functions) invocation.

<?php
class Methodtest 
{public
 function __call ($name, $arguments) {
  echo ' calling object method ' $ Name ' ". Implode (', ', $arguments). "\ n";
 }

 The public static function __callstatic ($name, $arguments) {
  echo calling static method ' $name '. Implode (', ', $arguments). "\ n";
 }
}

$obj = new Methodtest;
$obj->runtest (' in object context ');
Methodtest::runtest (' In the static context ');
? >

__get (), __set (), __isset () and __unset ()

These two functions are called when get/set a member variable of a class. For example, we save an object variable in another array, not as a member variable of the object itself.

<?php 
class Methodtest
{
 Private $data = Array ();

 Public Function __set ($name, $value) {
  $this->data[$name] = $value;
 }

 The Public Function __get ($name) {
  if (array_key_exists ($name, $this->data)) is return
   $this->data[$name];
  return NULL;
 }

 Public Function __isset ($name) {return
  isset ($this->data[$name])
 } public

 function unset ($name) {
  unset ($this->data[$name]);
 }
? >

__sleep () and __wakeup ()

When we execute serialize () and Unserialize (), the two functions are called first. For example, when serializing an object that has a database link, and wants to restore the link state in deserialization, you can refactor the two functions to achieve the link recovery. Examples are as follows:

<?php
class Connection 
{
 protected $link;
 Private $server, $username, $password, $db;

 Public function __construct ($server, $username, $password, $db)
 {
  $this->server = $server;
  $this->username = $username;
  $this->password = $password;
  $this->db = $db;
  $this->connect ();
 }

 Private function Connect ()
 {
  $this->link = mysql_connect ($this->server, $this->username, $this- >password);
  mysql_select_db ($this->db, $this->link);
 }

 Public Function __sleep ()
 {return
  array (' Server ', ' username ', ' password ', ' db ');
 }

 Public Function __wakeup ()
 {
  $this->connect ();
 }
? >

__tostring ()

The response method when the object is treated as a string. For example, using the Echo $obj to output an object

<?php
//Declare A simple class
class classes TestClass
{public
 function __tostring () {
  Object ';
 }
}

$class = new TestClass ();
echo $class;
? >

This method can only return a string and cannot throw an exception in this method, otherwise a fatal error can occur.

__invoke ()

The response method when calling an object in a way that calls a function. As follows

<?php
class Callableclass 
{
 function __invoke () {
  echo ' This is a object ';
 }
}
$obj = new Callableclass;
Var_dump (Is_callable ($obj));
>

__set_state ()

This static method is invoked when Var_export () is invoked to export the class.

<?php
class A
{public
 $var 1;
 Public $var 2;

 public static function __set_state ($an _array) {
  $obj = new A;
  $obj->var1 = $an _array[' var1 '];
  $obj->var2 = $an _array[' var2 '];
  return $obj;
 }

$a = new A;
$a->var1 = 5;
$a->var2 = ' foo ';
Var_dump (Var_export ($a));
>

__clone ()

Called when the object copy completes. For example, in the design mode and PHP implementation: A single example mode in the article mentioned in the single example mode implementation, using this function to prevent objects from being cloned.

<?php public 
class Singleton {
 private static $_instance = NULL;

 Private construction Method 
 Private Function __construct () {} public

 static function getinstance () {
  if Is_null (self::$_ Instance)) {
   self::$_instance = new Singleton ();
  }
  return self::$_instance;
 }

 Prevents the clone instance public
 function __clone () {
  die (' clone isn't allowed. '). e_user_error);
 }
? >

Magic Constants (Magic constants)

Most of the constants in PHP are invariant, but there are 8 constants that change as the location of their code changes, and these 8 constants are called Magic constants.

    • __line__, the current line number in the file
    • __file__, the full path and filename of the file
    • __dir__, the directory where the files are located
    • __function__, Function name
    • __class__, the name of the class
    • __trait__,trait's name.
    • __method__, the method name of the class
    • __namespace__, the name of the current namespace

These Magic constants are often used to obtain information about the current environment or to log logs.

The above is the entire content of this article, I hope to help you learn.

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.