Table of Contents
详解php魔术方法(Magic methods)的使用方法,magicmethods
您可能感兴趣的文章:
Home php教程 php手册 详解php魔术方法(Magic methods)的使用方法,magicmethods

详解php魔术方法(Magic methods)的使用方法,magicmethods

Jun 13, 2016 am 08:46 AM
magic methods php magic method

详解php魔术方法(Magic methods)的使用方法,magicmethods

PHP中把以两个下划线__开头的方法称为魔术方法,这些方法在PHP中充当了举足轻重的作用。 魔术方法包括:

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

__construct()和__destruct()

构造函数和析构函数应该不陌生,他们在对象创建和消亡时被调用。例如我们需要打开一个文件,在对象创建时打开,对象消亡时关闭

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<&#63;php

class FileRead

{

 protected $handle = NULL;

 

 function __construct(){

  $this->handle = fopen(...);

 }

 

 function __destruct(){

  fclose($this->handle);

 }

}

&#63;>

Copy after login

这两个方法在继承时可以扩展,例如:

1

2

3

4

5

6

7

8

9

10

11

12

<&#63;php

class TmpFileRead extends FileRead

{

 function __construct(){

  parent::__construct();

 }

 

 function __destruct(){

  parent::__destruct();

 }

}

&#63;>

Copy after login

__call()和__callStatic()

在对象中调用一个不可访问方法时会调用这两个方法,后者为静态方法。这两个方法我们在可变方法(Variable functions)调用中可能会用到。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<&#63;php

class 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');

&#63;>

Copy after login

__get(),__set(),__isset()和__unset()

当get/set一个类的成员变量时调用这两个函数。例如我们将对象变量保存在另外一个数组中,而不是对象本身的成员变量

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<&#63;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]);

 }

}

&#63;>

Copy after login

__sleep()和__wakeup()

当我们在执行serialize()和unserialize()时,会先调用这两个函数。例如我们在序列化一个对象时,这个对象有一个数据库链接,想要在反序列化中恢复链接状态,则可以通过重构这两个函数来实现链接的恢复。例子如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

<&#63;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();

 }

}

&#63;>

Copy after login

__toString()

对象当成字符串时的回应方法。例如使用echo $obj;来输出一个对象

1

2

3

4

5

6

7

8

9

10

11

12

<&#63;php

// Declare a simple class

class TestClass

{

 public function __toString() {

  return 'this is a object';

 }

}

 

$class = new TestClass();

echo $class;

&#63;>

Copy after login

这个方法只能返回字符串,而且不可以在这个方法中抛出异常,否则会出现致命错误。

__invoke()

调用函数的方式调用一个对象时的回应方法。如下

1

2

3

4

5

6

7

8

9

10

<&#63;php

class CallableClass

{

 function __invoke() {

  echo 'this is a object';

 }

}

$obj = new CallableClass;

var_dump(is_callable($obj));

&#63;>

Copy after login

__set_state()

调用var_export()导出类时,此静态方法会被调用。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<&#63;php

class 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));

&#63;>

Copy after login

__clone()

当对象复制完成时调用。例如在设计模式详解及PHP实现:单例模式一文中提到的单例模式实现方式,利用这个函数来防止对象被克隆。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<&#63;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('Clone is not allowed.' . E_USER_ERROR);

 }

}

&#63;>

Copy after login

魔术常量(Magic constants)

PHP中的常量大部分都是不变的,但是有8个常量会随着他们所在代码位置的变化而变化,这8个常量被称为魔术常量。

  • __LINE__,文件中的当前行号
  • __FILE__,文件的完整路径和文件名
  • __DIR__,文件所在的目录
  • __FUNCTION__,函数名称
  • __CLASS__,类的名称
  • __TRAIT__,Trait的名字
  • __METHOD__,类的方法名
  • __NAMESPACE__,当前命名空间的名称

这些魔术常量常常被用于获得当前环境信息或者记录日志。

以上就是本文的全部内容,希望对大家的学习有所帮助。

您可能感兴趣的文章:

  • php 魔术方法使用说明
  • 详解php的魔术方法__get()和__set()使用介绍
  • php魔术方法与魔术变量、内置方法与内置变量的深入分析
  • 基于PHP5魔术常量与魔术方法的详解
  • php教程之魔术方法的使用示例(php魔术函数)
  • ThinkPHP查询中的魔术方法简述
  • PHP类中的魔术方法(Magic Method)简明总结
  • PHP 5.3新增魔术方法__invoke概述
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

See all articles