Php反射
大苹果

Php反射

ReflectionClass::__construct(PHP5,PHP7)ReflectionClass::__construct—初始化ReflectionClass类说明publicReflectionClass::__construct(mixed$argument)初始化新的ReflectionClass对象。参数argument既可以是包含类名的字符串(string)也可以是对象(object)。返回值返回初始化完成后的ReflectionClass实例。错误/异常如果要反射的Class不存在,抛出异常ReflectionException。范例Example#1ReflectionClass的基本用法<?phpReflection::export(newReflectionClass('Exception'));?>以上例程的输出类似于:Class[<internal:Core>classException]{-Constants[0]{}-Staticproperties[0]{}-Staticmethods[0]{}-Properties[7]{Property[<default>protected$message]Property[<default>private$string]Property[<default>protected$code]Property[<default>protected$file]Property[<default>protected$line]Property[<default>private$trace]Property[<default>private$previous]}-Methods[10]{Method[<internal:Core>finalprivatemethod__clone]{}Method[<internal:Core,ctor>publicmethod__construct]{-Parameters[3]{Parameter#0[<optional>$message]Parameter#1[<optional>$code]Parameter#2[<optional>$previous]}}Method[<internal:Core>finalpublicmethodgetMessage]{}Method[<internal:Core>finalpublicmethodgetCode]{}Method[<internal:Core>finalpublicmethodgetFile]{}Method[<internal:Core>finalpublicmethodgetLine]{}Method[<internal:Core>finalpublicmethodgetTrace]{}Method[<internal:Core>finalpublicmethodgetPrevious]{}Method[<internal:Core>finalpublicmethodgetTraceAsString]{}Method[<internal:Core>publicmethod__toString]{}}}参见ReflectionObject::__construct()-ConstructsaReflectionObjectConstructorsaddanoteUserContributedNotes6notes3yearsagoExampleofusage:publicstaticfunctiongetClassData($class){//TryingtocreateanewobjectofReflectionClassclass$class=newReflectionClass($class);$details=sprintf('%s-%s%s%s%s%s%s%s%s',$class->getName(),$class->isInternal()?'internalclass,':'user-definedclass,',$class->isTrait()?'istrait,':'',$class->isInterface()?'isinterface,':'',$class->isAbstract()?'isabstract,':'',$class->isFinal()?'isfinal,':'',$class->isCloneable()?'iscloneable,':'',$class->isInstantiable()?'isinstantiable,':'',$class->isIterateable()?'isiterable:'');return'<preclass="debug">'.rtrim($details,',').'</pre>';}5yearsagoRunningthefollowingcodeonWindowsVista(Iknow,Iknow),PHP5.3.9,theReflectionClassconstructoractuallythrowsaReflectionExceptionwhenthedesiredclasscannotbeinstantiated:<?phptry{$ReflectedClass=newReflectionClass('NonExist');}catch(LogicException$Exception){die('Notgonnamakeitinhere...');}catch(ReflectionException$Exception){die('Yourclassdoesnotexist!');}?>7yearsagoIt'sveryusefultoknowthatyoucanalsousetheReflectionClasstoinspectinterfaces,eventhouthInterfacesarenotclasses.Example:<?phpinterfaceEdible{publicfunctioneat();}$refl=newReflectionClass("Edible");$methods=$refl->getMethods();?>[EditbydanbrownATphpDOTnet-Containsabugfixby(dblATbnetDOTcom)on18-AUG-2010withthefollowingmessage:"underlinehadtoberemovedforittowork(newReflection_Class->newReflectionClass)"]danbettlesatyahoodotcodotuk2yearsagoToreflectonanamespacedclassinPHP5.3,youmustalwaysspecifythefullyqualifiednameoftheclass-evenifyou'vealiasedthecontainingnamespaceusinga"use"statement.Soinsteadof:<?phpuseApp\CoreasCore;$oReflectionClass=newReflectionClass('Core\Singleton');?>Youwouldtype:<?phpuseApp\CoreasCore;$oReflectionClass=newReflectionClass('App\Core\Singleton');?>5yearsagoUsefultoknowthatifyoupassastringintotheconstructandtheclasscannotbeinstantiatedforsomereasonaSPLLogicExceptionwillbethrown.ThiscodewasranonaMacOSX10.6.7,AMP,PHP5.3+<?php//index.phptry{$ReflectedClass=newReflectionClass('NonExist');}catch(LogicException$logicDuh){print_r($logicDuh);}?>Willreturnadeeplynestedarrayfullofusefulinformationabouttheerror.3yearsagoif(is_file($classfile))require_once$classfile;if(!class_exists($classname,false))exit('ERROR:'.$classname.'isnotdefinedasaClass');Theabovecodeisusefultotelliftheclasswasdefined.YoucouldalsouseanothercommentorsmethodusingTryCatchExceptions.But,ifyoudonotusetryblocksmuch,theabovefunctionbasedmethodworksjustfine.Fromthere,youcanthancall:$class=newReflectionClass($classname);if(!$class->isSubclassOf('PanelCommon'))exit("ERROR:{$classname}mustextendsPanelCommon");if(!$class->isUserDefined())exit("ERROR:{$classname}mustbeuserdefinedandnotinternaltoPHP");if(!$class->IsInstantiable())exit("ERROR:{$classname}mustbeIsInstantiableandnotanInterfaceorAbstractclass");if(!$class->hasMethod('home'))exit("ERROR:{$classname}lacksrequiredmethod/functionhome()");Forforthandsoon.

PHP,反射,Reflection 3779 7年前
共 1 页