Home > Backend Development > PHP Tutorial > What is the magic method in php? Summary of the use of php magic methods (code)

What is the magic method in php? Summary of the use of php magic methods (code)

不言
Release: 2023-04-03 11:52:01
Original
5094 people have browsed it

The definition of magic methods in PHP is that methods starting with two underscores __ are called magic methods. The role of these magic methods in PHP is very important. Let’s take a look at examples of these magic methods.

Magic methods:

__construct(),类的构造函数
__destruct(),类的析构函数
__call(),在对象中调用一个不可访问方法时调用
__callStatic(),用静态方式中调用一个不可访问方法时调用
__get(),获得一个类的成员变量时调用
__set(),设置一个类的成员变量时调用
__isset(),当对不可访问属性调用isset()或empty()时调用
__unset(),当对不可访问属性调用unset()时被调用。
__sleep(),执行serialize()时,先会调用这个函数
__wakeup(),执行unserialize()时,先会调用这个函数
__toString(),类被当成字符串时的回应方法
__invoke(),调用函数的方式调用一个对象时的回应方法
__set_state(),调用var_export()导出类时,此静态方法会被调用。
__clone(),当对象复制完成时调用
Copy after login

__construct() and __destruct()

Constructor and destructor Functions should be familiar, they are called when objects are created and destroyed. For example, we need to open a file, open it when the object is created, and close it when the object dies

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

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

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

__call() and __callStatic()

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

<?php
class MethodTest
{
 public function __call ($name, $arguments) {
  echo "Calling object method &#39;$name&#39; ". implode(&#39;, &#39;, $arguments). "\n";
 }
 
 public static function __callStatic ($name, $arguments) {
  echo "Calling static method &#39;$name&#39; ". implode(&#39;, &#39;, $arguments). "\n";
 }
}
 
$obj = new MethodTest;
$obj->runTest(&#39;in object context&#39;);
MethodTest::runTest(&#39;in static context&#39;);
?>
Copy after login

__get(), __set(),

__get attribute is the __get method that is automatically loaded when the attribute in the access object does not exist or is not a public attribute. The parameter has only one name value, which is the name of the

attribute in the access object.

__set is when assigning a value to an attribute in an object. If the attribute does not exist or is a non-public attribute, the __set method will be automatically loaded. There are two parameters. Parameter 1 is the name of the uncallable attribute in the access object. Parameter 2 is the parameter to be passed for assignment. It can be an array or a string.

all have public visibility. Non-static, here is a small chestnut for easy understanding:

<?php
/**
 * 清晰的认识__get() __set()
 */
class Example {
    
    //公有的属性
    public $public = &#39;pub&#39; ;
    //受保护的 - 子类中该属性可用
    protected $protected = &#39;pro&#39;;
    //私有的 - 只能此类使用此属性
    private $private = &#39;pri&#39;;
    
    //当访问对象中的属性不存在或者非公有属性的时候自动加载__get()方法
    public function __get($name){
        return &#39;调用__get()方法:&#39;.$name;
    }
    
    //当给对象的一个属性赋值的时候如果该属性不存在或者是非公有属性则自动加载__set()方法
    public function __set($name,$value){
        echo "\nname:".$name.&#39;,value:&#39;.$value."\n";
    }
}
$example = new Example;
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
echo $example->public."\n";
echo $example->protected."\n";
echo $example->private."\n";
echo $example->other."\n";
echo &#39;<hr>&#39;;
$example->public = &#39;lic&#39;;   //这个赋值成功所有没有显示
$example->protected = &#39;tec&#39;;
$example->private = &#39;vat&#39;;
$example->other = &#39;er&#39;;
echo &#39;<br/>&#39;;
Copy after login

echo 'Print public attributes:'.$example->public;

__isset() and __unset()

__isset() calls attributes in an object or calls attributes in a non-class. When using the isset() method, if there is no or non-public attribute

, the isset() method will be automatically executed.

__unset() calls the attribute in the object or calls the attribute in the non-class. Use the unset() method. If there is no or non-public attribute, the call to __unset() will be executed automatically. You can Deletion of member attributes that cannot be called. If this method is not added to the class, any private members in the

object cannot be deleted.

Let’s give a little chestnut first:

<?php
    /**
     * 针对类中的魔术方法 __isset() 和 __unset() 的例子
     */
class Example {
    public $public;
    protected $protected;
    private $private;
    
    public function __construct(){
        $this->public = &#39;pub&#39;;
        $this->protected = &#39;pro&#39;;
        $this->private = &#39;pri&#39;;
    }
    
    public function __isset($var){
        echo &#39;这里通过__isset()方法查看属性名为 &#39;.$var."\n";
    }
    
    public function __unset($var){
        echo &#39;这里通过__unset()方法要销毁属性名为 &#39;.$var."\n";
    }
}
$exa = new Example;
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
var_dump(isset($exa->public));
echo "\n";
var_dump(isset($exa->protected));
echo "\n";
var_dump(isset($exa->private));
echo "\n";
var_dump(isset($exa->noVar));
echo "\n";
echo &#39;<hr/>&#39;;

unset($exa->public);
var_dump($exa);
echo "\n";
unset($exa->protected);
echo "\n";
unset($exa->private);
echo "\n";
unset($exa->noVar);
echo "\n";
Copy after login

__sleep() and __wakeup()

When we execute serialize() and unserialize(), these two functions will be called first. For example, when we serialize an object, the object has a database link. If we want to restore the link state during deserialization, we can restore the link by reconstructing these two functions. 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(&#39;server&#39;, &#39;username&#39;, &#39;password&#39;, &#39;db&#39;);
 }
 
 public function __wakeup()
 {
  $this->connect();
 }
}
?>
Copy after login

__toString()

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

<?php
// Declare a simple class
class TestClass
{
 public function __toString() {
  return &#39;this is a object&#39;;
 }
}
 
$class = new TestClass();
echo $class;
?>
Copy after login

This method can only return a string, and exceptions cannot be thrown in this method, otherwise a fatal error will occur.

__invoke()

The response method when calling an object by calling a function. as follows

<?php
class CallableClass
{
 function __invoke() {
  echo &#39;this is a object&#39;;
 }
}
$obj = new CallableClass;
var_dump(is_callable($obj));
?>
Copy after login

__set_state()

This static method will be called when calling var_export() to export a class.

<?php
class A
{
 public $var1;
 public $var2;
 
 public static function __set_state ($an_array) {
  $obj = new A;
  $obj->var1 = $an_array[&#39;var1&#39;];
  $obj->var2 = $an_array[&#39;var2&#39;];
  return $obj;
 }
}
 
$a = new A;
$a->var1 = 5;
$a->var2 = &#39;foo&#39;;
var_dump(var_export($a));
?>
Copy after login

__clone()

Called when the object copy is completed. For example, in the singleton mode implementation method mentioned in the article Detailed Explanation of Design Patterns and PHP Implementation: Singleton Mode, this function is used to prevent objects from being cloned.

<?php
public class Singleton {
 private static $_instance = NULL;
 
 // 私有构造方法
 private function __construct() {}
 
 public static function getInstance() {
  if (is_null(self::$_instance)) {
   self::$_instance = new Singleton();
  }
  return self::$_instance;
 }
 
 // 防止克隆实例
 public function __clone(){
  die(&#39;Clone is not allowed.&#39; . E_USER_ERROR);
 }
}
?>
Copy after login

Magic constants

Most of the constants in PHP are unchanged, but there are 8 constants that will change as their location in the code changes. These 8 A constant is called a magic constant.

__LINE__, the current line number in the file

__FILE__, the full path and file name of the file

__DIR__, the directory where the file is located

__FUNCTION__, function Name

__CLASS__, class name

__TRAIT__, Trait name

__METHOD__, class method name

__NAMESPACE__, name of current namespace

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

Related recommendations:

Several magic methods commonly used in PHP

[php classes and objects]Magic methods

The above is the detailed content of What is the magic method in php? Summary of the use of php magic methods (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template