How to use Magic methods in php, magicmethods

Source: Internet
Author: User

How to use Magic methods in php, magicmethods

In PHP, The Methods starting with two underscores _ are called magic methods, which play an important role in PHP. Magic methods include:

  • _ Construct (), constructor of the class
  • _ Destruct (): Class destructor
  • _ Call (), called when an inaccessible method is called in an object
  • _ CallStatic (), called when an inaccessible method is called in static mode
  • _ Get (), called when obtaining a class member variable
  • _ Set (), called when a class member variable is set
  • _ Isset (), called when isset () or empty () is called for inaccessible attributes
  • _ Unset () is called when unset () is called for an inaccessible attribute.
  • _ Sleep (): This function is called first when serialize () is executed.
  • _ Wakeup (): This function is called first when unserialize () is executed.
  • _ ToString (), the response method when the class is treated as a string
  • _ Invoke (): The response method when an object is called by calling a function
  • _ Set_state (): This static method is called when var_export () is called to export the class.
  • _ Clone (), called when the object copy is complete

_ Construct () and _ destruct ()

Constructor and destructor should not be unfamiliar. They are called when the object is created or eliminated. For example, we need to open a file, which is opened when the object is created, and closed when the object is killed.

<?php class FileRead{ protected $handle = NULL; function __construct(){  $this->handle = fopen(...); } function __destruct(){  fclose($this->handle); }}?>

These two methods can be extended during inheritance, for example:

<?php class TmpFileRead extends FileRead{ function __construct(){  parent::__construct(); } function __destruct(){  parent::__destruct(); }}?>

_ Call () and _ callStatic ()

When an inaccessible method is called in an object, the two methods are called, and the latter is a static method. These two methods may be used in Variable functions calls.

<?phpclass MethodTest { public function __call ($name, $arguments) {  echo "Calling object method '$name' ". implode(', ', $arguments). "\n"; } 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 static context');?>

_ Get () ,__ set () ,__ isset () and _ unset ()

These two functions are called when get/set is a member variable of a class. For example, we save the object variables in another array, instead of the member variables of the object.

<?php class MethodTest{ private $data = array(); public function __set($name, $value){  $this->data[$name] = $value; } public function __get($name){  if(array_key_exists($name, $this->data))   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 (), these two functions are called first. For example, when we serialize an object, this object has a database link. To restore the link status in deserialization, we can reconstruct these two functions to restore the link. Example:

<?phpclass 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 ()

Response method when the object is treated as a string. For example, echo $ obj; is used to output an object.

<?php// Declare a simple classclass TestClass{ public function __toString() {  return 'this is a 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 occurs.

_ Invoke ()

The response method when a function is called. As follows:

<?phpclass CallableClass { function __invoke() {  echo 'this is a object'; }}$obj = new CallableClass;var_dump(is_callable($obj));?>

_ Set_state ()

This static method is called when var_export () is called to export the class.

<?phpclass A{ public $var1; public $var2; 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 is complete. For example, detailed description of the design mode and PHP implementation: This function is used to prevent the object from being cloned.

<? Php public class Singleton {private static $ _ instance = NULL; // private constructor private function _ construct () {} public static function getInstance () {if (is_null (self:: $ _ instance) {self: $ _ instance = new Singleton ();} return self: $ _ instance ;} // prevent clone instance public function _ Clone () {die ('clone is not allowed. '. e_USER_ERROR) ;}}?>

Magic constants)

Most constants in PHP remain unchanged, but eight constants change with the change of their code location. These eight constants are called magic constants.

  • _ LINE __, current row number in the file
  • _ FILE __, full FILE path and FILE name
  • _ DIR __, directory of the file
  • _ FUNCTION __, FUNCTION name
  • _ CLASS __, CLASS Name
  • _ TRAIT __, Trait name
  • _ METHOD __, class METHOD name
  • _ NAMESPACE __, name of the current NAMESPACE

These magic constants are often used to obtain information about the current environment or record logs.

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Php magic methods
  • Describes how to use php magic methods _ get () and _ set ()
  • In-depth analysis of php magic methods and magic variables, built-in methods and built-in Variables
  • PHP5 magic constants and magic methods
  • Examples of magic methods used in php tutorials (php magic functions)
  • Magic methods in ThinkPHP Query
  • Magic Method in PHP
  • How to add magic method__ invoke in PHP 5.3

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.