Home php教程 php手册 PHP5魔术函数的具体应用讲解

PHP5魔术函数的具体应用讲解

Jun 13, 2016 am 11:06 AM
php5 specific function exist Example object application of explain magic

PHP5魔术函数1,__construct() 当实例化一个对象的时候,这个对象的这个方法首先被调用。

<ol class="dp-xml">
<li class="alt"><span><span>class Test   </span></span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span> function __construct()   </span></li>
<li class=""><span> {   </span></li>
<li class="alt"><span>  echo "before";   </span></li>
<li class=""><span> }   </span></li>
<li class="alt">
<span>}   </span><span></span><span></span>
</li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">t</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">new</font></span><span> Test();  </span>
</li>
</ol>
Copy after login

输出是:

start

我们知道php5对象模型 和类名相同的函数是类的构造函数,那么如果我们同时定义构造函数和__construct()方法的话,php5会默认调用构造函数而不会调用__construct()函数,所以__construct()作为类的默认的构造函数

PHP5魔术函数2,__destruct() 当删除一个对象或对象操作终止的时候,调用该方法。

<ol class="dp-xml">
<li class="alt"><span><span>class Test   </span></span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span> function __destruct()   </span></li>
<li class=""><span> {   </span></li>
<li class="alt"><span>  echo "end";   </span></li>
<li class=""><span> }   </span></li>
<li class="alt"><span>}   </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">t</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">new</font></span><span> Test(); </span>
</li>
</ol>
Copy after login

将会输出

end

我们就可以在对象操作结束的时候进行释放资源之类的操作

PHP5魔术函数3,__get() 当试图读取一个并不存在的属性的时候被调用。

如果试图读取一个对象并不存在的属性的时候,PHP就会给出错误信息。如果在类里添加__get方法,并且我们可以用这个函数实现类似java中反射的各种操作

<ol class="dp-xml">
<li class="alt"><span><span>class Test   </span></span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span> public function __get($key)   </span></li>
<li class=""><span> {   </span></li>
<li class="alt"><span>  echo $key . " 不存在";   </span></li>
<li class=""><span> }   </span></li>
<li class="alt"><span>}   </span></li>
<li class=""><span> </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">t</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">new</font></span><span> Test();   </span>
</li>
<li class="alt">
<span>echo $t-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>name;   </span>
</li>
<li class=""><span> </span></li>
<li class="alt"><span>就会输出:  </span></li>
<li class=""><span>name 不存在  </span></li>
</ol>
Copy after login

PHP5魔术函数4,__set() 当试图向一个并不存在的属性写入值的时候被调用。

<ol class="dp-xml">
<li class="alt"><span><span>class Test   </span></span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span> public function __set($key,$value)   </span></li>
<li class=""><span> {   </span></li>
<li class="alt"><span>  echo '对'.$key . "附值".$value;   </span></li>
<li class=""><span> }   </span></li>
<li class="alt"><span>}   </span></li>
<li class=""><span> </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">t</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">new</font></span><span> Test();   </span>
</li>
<li class="alt">
<span>$t-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span class="attribute"><font color="#ff0000">name</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">"aninggo"</font></span><span>;   </span>
</li>
<li class=""><span> </span></li>
<li class="alt"><span>就会输出:  </span></li>
<li class=""><span>对 name 附值 aninggo </span></li>
</ol>
Copy after login

PHP5魔术函数5,__call() 当试图调用一个对象并不存在的方法时,调用该方法。

<ol class="dp-xml">
<li class="alt"><span><span>class Test   </span></span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span> public function __call($Key, $Args)   </span></li>
<li class=""><span> {   </span></li>
<li class="alt"><span>  echo "您要调用的 {$Key} 方法不存在。你传入的参数是:" . print_r($Args, true);   </span></li>
<li class=""><span> }   </span></li>
<li class="alt"><span>}   </span></li>
<li class=""><span> </span></li>
<li class="alt">
<span>$</span><span class="attribute"><font color="#ff0000">t</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">new</font></span><span> Test();   </span>
</li>
<li class="">
<span>$t-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>getName(aning,go);  </span>
</li>
</ol>
Copy after login

程序将会输出:

您要调用的 getName 方法不存在。参数是:Array

(

[0] => aning

[1] => go

)

PHP5魔术函数6,__toString() 当打印一个对象的时候被调用

这个方法类似于java的toString方法,当我们直接打印对象的时候回调用这个函数

<ol class="dp-xml">
<li class="alt"><span><span>class Test   </span></span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span> public function __toString()   </span></li>
<li class=""><span> {   </span></li>
<li class="alt"><span>  return "打印 Test";   </span></li>
<li class=""><span> }   </span></li>
<li class="alt"><span>}   </span></li>
<li class=""><span> </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">t</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">new</font></span><span> Test();   </span>
</li>
<li class="alt"><span> </span></li>
<li class=""><span>echo $t;   </span></li>
</ol>
Copy after login

运行echo $t;的时候,就会调用$t->__toString();从而输出

打印 Test

PHP5魔术函数7,__clone() 当对象被克隆时,被调用

<ol class="dp-xml">
<li class="alt"><span><span>class Test   </span></span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span> </span></li>
<li class=""><span> public function __clone()   </span></li>
<li class="alt"><span> {   </span></li>
<li class=""><span>  echo "我被复制了!";   </span></li>
<li class="alt"><span> }   </span></li>
<li class=""><span>}  </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">t</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">new</font></span><span> Test();   </span>
</li>
<li class="alt">
<span>$</span><span class="attribute"><font color="#ff0000">t1</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">clone</font></span><span> $t;  </span>
</li>
<li class=""><span> </span></li>
<li class="alt"><span>程序输出:  </span></li>
<li class=""><span>我被克隆了! </span></li>
</ol>
Copy after login

PHP5魔术函数8.顺便介绍下php5中提供的几个非常COOl的实验性函数

(1)runkit_method_rename

这个函数可以动态的改变我们所调用的函数的名字。

<ol class="dp-xml">
<li class="alt"><span><span>class Test   </span></span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span> </span></li>
<li class=""><span> function foo() {  </span></li>
<li class="alt"><span>        return "foo! ";  </span></li>
<li class=""><span>    }  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>}   </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>runkit_method_rename(  </span></li>
<li class="alt"><span>    'Test', //类名  </span></li>
<li class=""><span>    'foo',//实际调用的函数  </span></li>
<li class="alt"><span>    'bar'//显示调用的函数  </span></li>
<li class=""><span>);  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>echo Test::bar();  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>程序将输出  </span></li>
<li class="alt"><span>   </span></li>
<li class=""><span>foo!  </span></li>
</ol>
Copy after login

(2) runkit_method_add

这个PHP5魔术函数可以动态的向类中添加函数

<ol class="dp-xml">
<li class="alt"><span><span>class Test   </span></span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span> </span></li>
<li class=""><span> function foo() {  </span></li>
<li class="alt"><span>        return "foo! ";  </span></li>
<li class=""><span>    }  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>}   </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>runkit_method_add(  </span></li>
<li class="alt"><span>    Test,  //类名  </span></li>
<li class=""><span>    'add', //新函数名  </span></li>
<li class="alt"><span>    '$num1, $num2',//传入参数  </span></li>
<li class=""><span>    'return $num1 + $num2;',//执行的代码  </span></li>
<li class="alt"><span>    RUNKIT_ACC_PUBLIC  </span></li>
<li class=""><span>);  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>// 调用   </span></li>
<li class="alt">
<span>echo $e-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>add(12, 4); </span>
</li>
</ol>
Copy after login

(3)runkit_method_copy

可以把A类中的函数拷贝到类B中并对PHP5魔术函数重命名

<ol class="dp-xml">
<li class="alt"><span><span>class Foo {  </span></span></li>
<li class=""><span>    function example() {  </span></li>
<li class="alt"><span>        return "foo! ";  </span></li>
<li class=""><span>    }  </span></li>
<li class="alt"><span>}  </span></li>
<li class=""><span> </span></li>
<li class="alt"><span>class Bar {  </span></li>
<li class=""><span>    //空类  </span></li>
<li class="alt"><span>}  </span></li>
<li class=""><span> </span></li>
<li class="alt"><span>//执行拷贝  </span></li>
<li class=""><span>runkit_method_copy('Bar', 'baz', 'Foo', 'example');  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>//执行拷贝后的函数  </span></li>
<li class="alt"><span>echo Bar::baz();  </span></li>
</ol>
Copy after login

(4) runkit_method_redefine

动态的修改函数的返回值

这个PHP5魔术函数可以让我们轻松的实现对类的MOCK测试!是不是很COOL呢

  1. class Example {  
  2.     function foo() {  
  3.         return "foo! ";  
  4.     }  
  5. }  
  6. //创建一个测试对象  
  7. $e = new Example();  
  8. // 在测试对象之前输出  
  9. echo "Before: " . $e->foo();  
  10. // 修改返回值  
  11. runkit_method_redefine(  
  12.     'Example',  
  13.     'foo',  
  14.     '',  
  15.     'return "bar! ";',  
  16.     RUNKIT_ACC_PUBLIC  
  17. );  
  18. // 执行输出  
  19. echo "After: " . $e->foo();  

(5)runkit_method_remove

这个PHP5魔术函数就很简单了,看名字就能看出来了,动态的从类中移除函数

<ol class="dp-xml">
<li class="alt"><span><span>class Test {  </span></span></li>
<li class=""><span>    function foo() {  </span></li>
<li class="alt"><span>        return "foo! ";  </span></li>
<li class=""><span>    }  </span></li>
<li class="alt"><span>      </span></li>
<li class=""><span>    function bar() {  </span></li>
<li class="alt"><span>        return "bar! ";  </span></li>
<li class=""><span>    }  </span></li>
<li class="alt"><span>}  </span></li>
<li class=""><span> </span></li>
<li class="alt"><span>// 移除foo函数  </span></li>
<li class=""><span>runkit_method_remove(  </span></li>
<li class="alt"><span>    'Test',  </span></li>
<li class=""><span>    'foo'  </span></li>
<li class="alt"><span>);  </span></li>
<li class=""><span> </span></li>
<li class="alt"><span>echo implode(' ', get_class_methods('Test'));  </span></li>
<li class=""><span> </span></li>
<li class="alt"><span>程序输出  </span></li>
<li class=""><span>bar  </span></li>
</ol>
Copy after login

以上所介绍的代码就是关于PHP5魔术函数的具体应用方式。


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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months 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)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What is the difference between arrays and objects in PHP? What is the difference between arrays and objects in PHP? Apr 29, 2024 pm 02:39 PM

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values ​​are passed and object references are passed.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

See all articles