搜索
首页后端开发php教程php5戏法函数、魔术常量

php5魔术函数、魔术常量

转自http://www.loveiso.com/article/11-06-11/48.html

魔术函数

1。__construct()
实例化对象时被调用,
当__construct和以类名为函数名的函数同时存在时,__construct将被调用,另一个不被调用。

2。__destruct()
当删除一个对象或对象操作终止时被调用。

3。__call()
对象调用某个方法,
若方法存在,则直接调用;
若不存在,则会去调用__call函数。

4。__get()
读取一个对象的属性时,
若属性存在,则直接返回属性值;
若不存在,则会调用__get函数。

5。__set()
设置一个对象的属性时,
若属性存在,则直接赋值;
若不存在,则会调用__set函数。

6。__toString()
打印一个对象的时被调用。如echo $obj;或print $obj;

7。__clone()
克隆对象时被调用。如:$t=new Test();$t1=clone $t;

8。__sleep()
serialize之前被调用。若对象比较大,想删减一点东东再序列化,可考虑一下此函数。

9。__wakeup()
unserialize时被调用,做些对象的初始化工作。

10。__isset()
检测一个对象的属性是否存在时被调用。如:isset($c->name)。

11。__unset()
unset一个对象的属性时被调用。如:unset($c->name)。

12。__set_state()
调用var_export时,被调用。用__set_state的返回值做为var_export的返回值。

13。__autoload()
实例化一个对象时,如果对应的类不存在,则该方法被调用。

魔术常量

1。__LINE__
返回文件中的当前行号。

2。__FILE__
返回文件的完整路径和文件名。如果用在包含文件中,则返回包含文件名。自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对路径,而在此之前的版本有时会包含一个相对路径。

3。__FUNCTION__
返回函数名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该函数被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。

4。__CLASS__
返回类的名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该类被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。

5。__METHOD__
返回类的方法名(PHP 5.0.0 新加)。返回该方法被定义时的名字(区分大小写)。




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


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

class Test
{
public function __get($key)
{
? echo $key . " 不存在";
}
}


$t = new Test();
echo $t->name;

就会输出:
name 不存在
4,__set() 当试图向一个并不存在的属性写入值的时候被调用。 class Test
{
public function __set($key,$value)
{
? echo '对'.$key . "附值".$value;
}
}


$t = new Test();
$t->name = "aninggo";

就会输出:
对 name 附值 aninggo
5,__call() 当试图调用一个对象并不存在的方法时,调用该方法。 class Test
{
public function __call($Key, $Args)
{
? echo "您要调用的 {$Key} 方法不存在。你传入的参数是:" . print_r($Args, true);
}
}

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

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

class Test
{
public function __toString()
{
? return "打印 Test";
}
}


$t = new Test();

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

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

class Test
{

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

$t = new Test();
$t1 = clone $t;

程序输出:
我被复制了

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Apple iPhone 16 Pro as Leica smartphone: Leica subsidiary confirms camera grip with official Leica appApple iPhone 16 Pro as Leica smartphone: Leica subsidiary confirms camera grip with official Leica appJun 13, 2024 pm 08:52 PM

LeicareleasedtheLeicaLuxcameraappfortheAppleiPhoneafewdaysago.However,theappwasnotdevelopedbyLeica,butbyFjorden.ThecompanyhasbeenknownprimarilyforitscameragripsfortheiPhoneandwasacquiredbyLeicainDecember2023.Fo

Remote 3 universal remote control comes with touchscreen, but without subscription or server obligationRemote 3 universal remote control comes with touchscreen, but without subscription or server obligationJun 14, 2024 am 09:13 AM

SincethedemiseofLogitech'spopularHarmonyremotecontrols,themarketforhigh-qualityuniversalremotecontrolshasbeenfragmentedatbest.UnfoldedCircleaimstoavoidthefateoftheHarmonyUltimatebyeliminatinganyserverobligationsorsubs

Samsung Galaxy S24 Ultra gains E Ink secondary display via inventive protective caseSamsung Galaxy S24 Ultra gains E Ink secondary display via inventive protective caseJun 14, 2024 am 10:44 AM

Anintriguingthird-partycasefortheGalaxyS24Ultra(curr.$1,099.99onAmazon)hasappearedonmarketplaceslikeAliExpress.Astheimagesthroughoutthisarticleshow,thecasehasasimplesiliconeconstruction.However,italsocontainsanEInkd

Electric Ferraris will boast an \'authentic\' growl, claims marketing executiveElectric Ferraris will boast an \'authentic\' growl, claims marketing executiveJun 14, 2024 am 10:26 AM

In2012,theeminentautomotivejournalistJeremyClarksonstatedthattheLamborghiniAventador,whichhewasreviewingatthetime,wouldbeamongthelastcarstofeatureanaturallyaspiratedV12.Morethanadecadelater,V12-poweredsupercarsareal

Light Phone 3 launches with 50% discount, monochrome OLED and minimalist designLight Phone 3 launches with 50% discount, monochrome OLED and minimalist designJun 13, 2024 pm 10:18 PM

WhiletheLightPhone2from2018wasstillequippedwithaneconomicale-inkdisplay,theLightPhone3usesanOLEDdisplaythatcanonlydisplaygrayscale.Thereasonfortheswitchtothe3.92-inchOLEDpanelwithitsresolutionof1,240x1,080isth

Audio-Technica unveils ATH-S300BT wireless headphones with hear-through noise-cancellation, 90 hours battery life, and multipoint pairingAudio-Technica unveils ATH-S300BT wireless headphones with hear-through noise-cancellation, 90 hours battery life, and multipoint pairingJun 14, 2024 am 09:46 AM

Audio-TechnicahasunveiledtheATH-S300BTwirelessheadphoneswithhear-throughnoise-cancellation,multipointpairing,and90hoursofbatterylife.Thenoise-cancellingfeaturehasthreemodes:off,on,andhear-through,whereambientsoundscanbehea

First complete PCIe 7.0 IP solution presented by Synopsys coming to market in 2025 for HPCs and AI supercomputersFirst complete PCIe 7.0 IP solution presented by Synopsys coming to market in 2025 for HPCs and AI supercomputersJun 14, 2024 am 09:19 AM

Backin2022,whenPCIe7.0wasstartingtotakeshapeasafuturestandard,PCIe5.0wasjusthittingtheservermarketsandtheprospectofseeingPCIe6.0devicesavailableanytimesoon,letalonePCIe7.0ones,wasquitefar-fetched.CurrentlyPCIe5

Jabra discontinues Elite wireless earbuds lineupJabra discontinues Elite wireless earbuds lineupJun 14, 2024 am 09:39 AM

TheJabraEliteserieshascometoanend,withGNCEOPeterKarlstromerannouncingthediscontinuationofthewirelessearbudswithinthelineupinapressrelease.Petersaysthatthechangingmarketdynamicsandhowchallengingithasbecometogetas

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),