搜尋
首頁後端開發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尊渡假赌尊渡假赌尊渡假赌

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版