PHP dynamically loads third-party classes and obtains class source code through reflection _ php instance

Source: Internet
Author: User
This article mainly introduces how PHP dynamically loads third-party classes and obtains class source code through reflection, which is generally used for parsing XML files. For more information, see Dynamic Loading of third-party classes using reflection

Loading third-party classes with reflection is useful in:
Configure the class to be loaded using XML or other configuration files to separate the class from the system source code.
Perform a class check on the loaded class. The loaded class conforms to its own defined structure.

<? Php abstract class Module {# core Module class library function baseFunc () {echo "I am baseFunc";} abstract function execute ();} class ModuleRunner {private $ configData = array (# simulate xml configuration, dynamically configure the Module to be loaded "PersonModule" => array ("person" => "bob "), "FtpModule" => array ("host" => "example.com", "user" => "anon"); private $ modules = array (); function init () {# initialize ModuleRunner and load Module $ parent = new Reflecti IN THE CONFIGURATION OnClass ("Module"); foreach ($ this-> configData as $ moduleName => $ params) {# Check whether the Module in the configuration is valid $ moduleClass = new ReflectionClass ($ moduleName ); if (! $ ModuleClass-> isSubclassOf ($ parent) {# check whether it is a Module subtype throw new Exception ("unknown type: {$ moduleName }");} $ module = $ moduleClass-> newInstance (); foreach ($ moduleClass-> getMethods () as $ method) {# Check whether the parameter format of the function in the configuration is correct $ this-> handleMothod ($ module, $ method, $ params);} array_push ($ this-> modules, $ module ); # Load Module} private function handleMothod (Module $ module, ReflectionMethod $ method, $ params) {# Check whether the method parameters in the Module are

No. It is the same as the $ params name and has the set method.

$ Name = $ method-> getName (); $ args = $ method-> getParameters (); if (count ($ args )! = 1 | substr ($ name, 0, 3 )! = "Set") {# if the number of parameters of the method without the configured class is not 1, or the first three letters of the method name are not set, false return false ;} $ property = strtolower (substr ($ name, 3); if (! Isset ($ params [$ property]) {# If the last three letters of the method name are different from the parameter name in the configuration, false return false ;} $ argClass = $ args [0]-> getClass (); # obtain the parameter type if (empty ($ argClass) {$ method-> invoke ($ module, $ params [$ property]); # Call the set method directly if the parameter has no type restriction} else {$ method-> invoke ($ module, $ argClass-> newInstance ($ params [$ property]); # create an instance with type restrictions and call the set method.} public function getModules () {return $ this-> modules;} class Person {# third-party class public $ nam E; function _ construct ($ name) {$ this-> name = $ name ;}} class FtpModule extends Module {# custom third-party Module private $ host = "default host"; private $ user = "default user"; function setHost ($ host) {$ this-> host = $ host;} function setUser ($ user) {$ this-> user = $ user;} function execute () {echo "{$ this-> user} user {$ this-> host}" ;}} class PersonModule extends Module {# custom third-party Module private $ pers On; function setPerson (Person $ person) {$ this-> person = $ person;} function execute () {if (isset ($ person )) {echo "I am {$ this-> person-> name}";} else {echo "I am no user" ;}}$ modRunner = new ModuleRunner (); $ modRunner-> init (); var_dump ($ modRunner);?>

Output

object(ModuleRunner)#1 (2) { ["configData":"ModuleRunner":private]=> array(2) { ["PersonModule"]=> array(1) { ["person"]=> string(3) "bob" } ["FtpModule"]=> array(2) { ["host"]=> string(11) "example.com" ["user"]=> string(4) "anon" } } ["modules":"ModuleRunner":private]=> array(2) { [0]=> object(PersonModule)#4 (1) { ["person":"PersonModule":private]=> object(Person)#10 (1) { ["name"]=> string(3) "bob" } } [1]=> object(FtpModule)#3 (2) { ["host":"FtpModule":private]=> string(11) "example.com" ["user":"FtpModule":private]=> string(4) "anon" } } }

Obtain class source code through reflection

<? Php function getSource (ReflectionClass $ ref) {$ path = $ ref-> getFileName (); # Get the script file name $ file = file ($ path); # file () method to get the file content and save the content in an array. Each element of the array saves a row of content $ start = $ ref-> getStartLine (); # obtain the row number of the class in the script $ end = $ ref-> getEndLine (); # Get the row number of the class in the last line of the script $ source = implode (array_slice ($ file, $ start-1, $ end-$ start + 1 )); # assembled class source code var_dump ($ source);} class Person {public $ age; private $ name; function say () {echo "Yes" ;}}$ ref = new ReflectionClass ("Person"); getSource ($ ref);?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.