简体   繁体   中英

PHP can I create an object of the class if I dynamically have access to the codes of class?

This is something weird but I want to create an object of a class that is stored in another file and I have the path to file but not the name of the class. the scenario is, there are many files stored in a directory and every file contains one class only. out of this directory is another file in which I an developing a function that takes the name of file, access the file and fetch the codes out of it then create an object of the class in that file and return the object. I am sure that it is possible but cant get it to work. Can anybody help me ?

Compare the results of get_declared_classes() before and after you include the file using array_diff() :

<?php

  $before = get_declared_classes();
  include_once('path/to/file');
  $after = get_declared_classes();

  $newClasses = array_diff($after, $before);

  for ($i = 0; isset($newClasses[$i]); $i++) {
    ${'class'.$i} = new $newClasses[$i];
    echo "New class $newClasses[$i] instantiated in variable \$class$i\n";
  }

You can use get_declared_classes()

Eg:

$klass = end(get_declared_classes());
$obj = new $klass;

this is simple but not very secure.

1.Load the source file as text, match the content for a regexp that will return the name of the class in $classname.

2.Do any check you need to ensure this class is wanted in your "loading process" based on the source code text , like extracting constructor parameters.

  1. require_once('the_file.php')

  2. $my_new_instance=new $classname() (given you have no constructor parameters) or $my_new_instance=new $classname($param1,$param2) given you have extracted parameters $param1,$param2 from source analysis phase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM