찾다
백엔드 개발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

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

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

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

TheJabraEliteserieshascometoanend,withGNCEOPeterKarlstromerannouncingthediscontinuationofthewirelessearbudswithinthelineupinapressrelease.Petersaysthatthechangingmarketdynamicsandhowchallengingithasbecometogetas

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

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경