Table of Contents
__set_state and __invoke" >__set_state and __invoke
Home Backend Development PHP Tutorial Php幻术函数学习与应用 _construct() _destruct() _get()等

Php幻术函数学习与应用 _construct() _destruct() _get()等

Jun 13, 2016 pm 01:02 PM
autoload class echo function test

Php魔术函数学习与应用 __construct() __destruct() __get()等

(1)初识魔术方法
Php5.0发布以来为我们提供了很多面向对象?的特性,尤其是为我们提供了好多易用的魔术方法,这些魔术方法可以让我们简化我们的编码,更好的设计我们的系统。今天我们就来认识下php5.0给我们提供的魔术方法。

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

<span style="background-color: #ffffff;">class Test
{
function __construct()

{
echo "before";
}
}

$t = new Test();</span>
Copy after login

?
输出是:

start



<span style="background-color: #ffffff;"><?
class Test
{
    function Test()
{
echo "end2";
}
function __construct()
{
echo "end";
}

}
$t = new Test();</span>
Copy after login
?

//输出end


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


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

<span style="background-color: #ffffff;">class Test
{
function __destruct()
{
echo "end";
}
}
$t = new Test();</span>
Copy after login

?
将会输出
end


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

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

<span style="background-color: #ffffff;">class Test
{
public function __get($key)
{
echo $key . " 不存在";
}
}

$t = new Test();
echo $t->name;</span>
Copy after login

?

就会输出:
name 不存在

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

<span style="background-color: #ffffff;">class Test
{
public function __set($key,$value)
{
echo '对'.$key . "附值".$value;
}
}


$t = new Test();
$t->name = "aninggo";</span>
Copy after login

?

就会输出:
对 name 附值 aninggo


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

<span style="background-color: #ffffff;">class Test
{
public function __call($Key, $Args)
{
echo "您要调用的 {$Key} 方法不存在。你传入的参数是:" . print_r($Args, true);
}
}

$t = new Test();
$t->getName(aning,go);</span>
Copy after login

?

程序将会输出:
您要调用的 getName 方法不存在。参数是:Array
(
[0] => aning
[1] => go
)

6,__toString() 当打印一个对象的时候被调用
这个方法类似于java的toString方法,当我们直接打印对象的时候回调用这个函数?

<span style="background-color: #ffffff;">class Test
{
public function __toString()
{
return "打印 Test";
}
}

$t = new Test();

echo $t; </span>
Copy after login

?

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

7,__clone() 当对象被克隆时,被调用

<span style="background-color: #ffffff;">class Test
{

public function __clone()
{
echo "我被复制了!";
}
}

$t = new Test();
$t1 = clone $t;</span>
Copy after login

?

程序输出:
我被克隆了!


__sleep 和 __wakeup



串行化serialize可以把变量包括对象,转化成连续bytes数据. 你可以将串行化后的变量存在一个文件里或在网络上传输. 然后再反串行化还原为原来的数据. 你在反串行化类的对象之前定义的类,PHP可以成功地存储其对象的属性和方法. 有时你可能需要一个对象在反串行化后立即执行. 为了这样的目的,PHP会自动寻找__sleep和__wakeup方法.

  当一个对象被串行化,PHP会调用__sleep方法(如果存在的话). 在反串行化一个对象后,PHP 会调用__wakeup方法. 这两个方法都不接受参数. __sleep方法必须返回一个数组,包含需要串行化的属性. PHP会抛弃其它属性的值. 如果没有__sleep方法,PHP将保存所有属性.

  例子6.16显示了如何用__sleep和__wakeup方法来串行化一个对象. Id属性是一个不打算保留在对象中的临时属性. __sleep方法保证在串行化的对象中不包含id属性. 当反串行化一个User对象,__wakeup方法建立id属性的新值. 这个例子被设计成自我保持. 在实际开发中,你可能发现包含资源(如图像或数据流)的对象需要这些方法

<span style="background-color: #ffffff;">Object serialization
CODE: [Copy to clipboard]
--------------------------------------------

<?php 

class User 
{ 
public $name; 
public $id; 

function __construct() 
{ 
//give user a unique ID 赋予一个不同的ID 
$this->id = uniqid(); 
} 

function __sleep() 
{ 
//do not serialize this->id 不串行化id 
return(array("name")); 
} 

function __wakeup() 
{ 
//give user a unique ID 
$this->id = uniqid(); 
} 
} 

//create object 建立一个对象 
$u = new User; 
$u->name = "Leon"; 

//serialize it 串行化 注意不串行化id属性,id的值被抛弃 
$s = serialize($u); 

//unserialize it 反串行化 id被重新赋值 
$u2 = unserialize($s); 

//$u and $u2 have different IDs $u和$u2有不同的ID 
print_r($u); 
print_r($u2); 
?></span>
Copy after login
?


__set_state and __invoke


测试代码如下:


<span style="background-color: #ffffff;"><?php
class A {
public static function __set_state($args)
 {
        $obj = new A();
        foreach($args as $k=>$v)
        {
             $obj->$k = $v;
        }
        return $obj;
    }

}
$a = new A;
$a->name = 'cluries';
$a->sex = 'female';
eval('$b = ' . var_export($a, true) . ';');
print_r($b);
?></span>
Copy after login
??

程序输出

<span style="background-color: #ffffff;">object(A)#2 (2) {
         ["name"]=>  string(7) "cluries"
         ["sex"]=>  string(6) "female"
}
</span>
Copy after login

得出以下结论,__set_state作用是用来复制一个对象,并且可以在__set_state中定义在复制对象的时候对复制得到的对象进行一些 改变。和__clone不同的是__set_state可以接受参数,__set_state使用起来更加强大!虽然个人觉得这个东西不是很好用= =!



然后再说下__invoke:
手册上有个非常显眼的:Note: This feature is available since PHP 5.3.0.?

<span style="background-color: #ffffff;">The __invoke method is called when a script tries to call an object as a function.
</span>
Copy after login

__invoke方法将会在代码试图把对象当作函数来使用时候调用?有点稀奇,这个功能有什么用处呢?
然后看下提供的例子:


<span style="background-color: #ffffff;"><?php
class CallableClass 
{
   function __invoke($x)
   {
        var_dump($x);
}
   }

$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>
</span>
Copy after login
?


程序输出:

<span style="background-color: #ffffff;">int(5)
bool(true)
</span>
Copy after login

还真是把对象当函数使用…


__autoload



PHP5中有一方法: __autoload() , 简单的说就是类的自动加载;

当你尝试使用一个PHP没有组织到的类, 它会寻找一个__autoload的全局函数. 如果存在这个函数,PHP会用一个参数来调用它,参数即类的名称。

那么简单测试一下。


首先建一个名为”Test_autoload.php”的文件:


<span style="background-color: #ffffff;">< ? php
/**
* 测试__autoload方法
*
*/
class Test_autoload {
public function __construct () {
echo " Test_autoload. " ;
}
}
?></span>
Copy after login
?

注意类名哦?, 然后随便建个文件重写 __autoload() 方法,这里假设是”test.php”;


<span style="background-color: #ffffff;">< ? php
/**
* 重写 __autoload方法
*/
function __autoload ( $class ) {
include $class . ' .php ' ;
}

$test = new Test_autoload () ;
unset ( $test ) ;
?></span>
Copy after login
?

最后结果为:Test_autoload.



------------------------------------------------
8.顺便介绍下php5中提供的几个非常COOl的实验性函数?
(1)。runkit_method_rename
??? 这个函数?可以动态的改变我们所调用的函数?的名字?。

<span style="background-color: #ffffff;">class Test
{

function foo() {
        return "foo! ";
    }

}

runkit_method_rename(
    'Test', //类名
    'foo',//实际调用的函数 
    'bar'//显示调用的函数 
);

echo Test::bar();</span>
Copy after login

?

程序将输出
 
foo!

(2) runkit_method_add

这个函数?可以动态的向类中添加函数?


<span style="background-color: #ffffff;">class Test
{

function foo() {
        return "foo! ";
    }

}

runkit_method_add(
    Test, //类名
    'add', //新函数 名
    '$num1, $num2',//传入参数
    'return $num1 + $num2;',//执行的代码
    RUNKIT_ACC_PUBLIC
);

// 调用
echo $e->add(12, 4);
</span>
Copy after login

?

(3)runkit_method_copy
可以把A类中的函数?拷贝到类B中并对函数?重命名


<span style="background-color: #ffffff;">class Foo {
    function example() {
        return "foo! ";
    }
}

class Bar {
    //空类
}

//执行拷贝
runkit_method_copy('Bar', 'baz', 'Foo', 'example');

//执行拷贝后的函数 
echo Bar::baz();
</span>
Copy after login

?

(4) runkit_method_redefine
动态的修改函数?的返回值
这个函数?可以让我们轻松的实现对类的MOCK测试!是不是很COOL呢


<span style="background-color: #ffffff;">class Example {
    function foo() {
        return "foo! ";
    }
}

//创建一个测试对象
$e = new Example();

// 在测试对象之前输出
echo "Before: " . $e->foo();

// 修改返回值
runkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar! ";',
    RUNKIT_ACC_PUBLIC
);

// 执行输出
echo "After: " . $e->foo();</span>
Copy after login

?


(5)runkit_method_remove
这个函数?就很简单了,看名字?就能看出来了,动态的从类中移除函数?

<span style="background-color: #ffffff;">class Test {
    function foo() {
        return "foo! ";
    }
   
    function bar() {
        return "bar! ";
    }
}

// 移除foo函数 
runkit_method_remove(
    'Test',
    'foo'
);

echo implode(' ', get_class_methods('Test'));</span>
Copy after login

?

程序输出
bar

?

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)

Huawei Watch GT 5 smartwatch gets update with new features Huawei Watch GT 5 smartwatch gets update with new features Oct 03, 2024 am 06:25 AM

Huawei is rolling out software version 5.0.0.100(C00M01) for the Watch GT 5 and the Watch GT 5 Prosmartwatchesglobally. These two smartwatches recently launched in Europe, with the standard model arriving as the company’s cheapest model. This Harmony

Tekken\'s Colonel Sanders dream fried by KFC Tekken\'s Colonel Sanders dream fried by KFC Oct 02, 2024 am 06:07 AM

Katsuhiro Harada, the Tekken series director, once seriously tried to bring Colonel Sanders into the iconic fighting game. In an interview with TheGamer, Harada revealed that he pitched the idea to KFC Japan, hoping to add the fast-food legend as a g

First look: Leaked unboxing video of upcoming Anker Zolo 4-port 140W wall charger with display First look: Leaked unboxing video of upcoming Anker Zolo 4-port 140W wall charger with display Oct 01, 2024 am 06:32 AM

Earlier in September 2024, Anker's Zolo 140W charger was leaked, and it was a big deal since it was the first-ever wall charger with a display from the company. Now, a new unboxing video from Xiao Li TV on YouTube gives us a first-hand look at the hi

Samsung Galaxy Z Fold Special Edition revealed to land in late October as conflicting name emerges Samsung Galaxy Z Fold Special Edition revealed to land in late October as conflicting name emerges Oct 01, 2024 am 06:21 AM

The launch of Samsung's long-awaited 'Special Edition' foldable has taken another twist. In recent weeks, rumours about the so-called Galaxy Z Fold Special Edition went rather quiet. Instead, the focus has shifted to the Galaxy S25 series, including

New Xiaomi Mijia Graphene Oil Heater with HyperOS arrives New Xiaomi Mijia Graphene Oil Heater with HyperOS arrives Oct 02, 2024 pm 09:02 PM

Xiaomi will shortly launch the Mijia Graphene Oil Heater in China. The company recently ran a successful crowdfunding campaign for the smart home product, hosted on its Youpin platform. According to the page, the device has already started to ship to

Garmin releases Adventure Racing activity improvements for multiple smartwatches via new update Garmin releases Adventure Racing activity improvements for multiple smartwatches via new update Oct 01, 2024 am 06:40 AM

Garmin is ending the month with a new set of stable updates for its latest high-end smartwatches. To recap, the company released System Software 11.64 to combat high battery drain across the Enduro 3, Fenix E and Fenix 8 (curr. $1,099.99 on Amazon).

Cybertruck FSD reviews praise quick lane switching and full-screen visualizations Cybertruck FSD reviews praise quick lane switching and full-screen visualizations Oct 01, 2024 am 06:16 AM

Tesla is rolling out the latest Full Self-Driving (Supervised) version 12.5.5 and with it comes the promised Cybertruck FSD option at long last, ten months after the pickup went on sale with the feature included in the Foundation Series trim price. F

Manjaro 24.1 \'Xahea\' launches with KDE Plasma 6.1.5, VirtualBox 7.1, and more Manjaro 24.1 \'Xahea\' launches with KDE Plasma 6.1.5, VirtualBox 7.1, and more Oct 02, 2024 am 06:06 AM

With a history of over one decade, Manjaro is regarded as one of the most user-friendly Linux distros suitable for both beginners and power users, being easy to install and use. Mostly developed in Austria, Germany, and France, this Arch-based distro

See all articles