Dynamically generate classes at runtime in php?

后端 未结 10 998
一向
一向 2020-12-09 15:06

Here\'s what I want to do:

$clsName = substr(md5(rand()),0,10); //generate a random name
$cls = new $clsName(); //create a new instance

function __autoload(         


        
相关标签:
10条回答
  • 2020-12-09 15:44

    This is almost certainly a bad idea.

    I think your time would be better spent creating a script that would create your class definitions for you, and not trying to do it at runtime.

    Something with a command-line signature like:

    ./generate_classes_from_db <host> <database> [tables] [output dir]
    
    0 讨论(0)
  • 2020-12-09 15:44

    Please read everyone else answers on how this is truly a very very bad idea.

    Once you understand that, here is a small demo on how you could, but should not, do this.


    <?php
    $clname = "TestClass";
    
    eval("class $clname{}; \$cls = new $clname();");
    
    var_dump($cls);
    
    0 讨论(0)
  • 2020-12-09 15:45

    I think using eval() it's not a reliable solution, especially if your script or software will be distributed to different clients. Shared hosting providers always disable eval() function.

    I'm thinking of a better aproach like this :

    <?php 
    
     function __autoload( $class ) {
          require 'classes/'.$class.'.php';
    
    }
    
    $class = 'App';
    $code = "<?php class $class {
        public function run() {
            echo '$class<br>';  
        }
        ".'
        public function __call($name,$args) {
            $args=implode(",",$args);
            echo "$name ($args)<br>";
        }
    }';
    
    file_put_contents('classes/App.php' ,$code);
    
    $a = new $class();
    $a->run();
    

    After finishing executing the code, you can delete the file if you want, I tested it and it works perfectly.

    0 讨论(0)
  • 2020-12-09 15:46
    function __autoload($class)  {
        $code = "class $class {`
            public function run() {
                echo '$class<br>';  
            }
            ".'
            public function __call($name,$args) {
                $args=implode(",",$args);
                echo "$name ($args)<br>";
            }
        }';
    
        eval($code);
    }
    
    $app=new Klasse();
    $app->run();
    $app->HelloWorld();
    

    This might help to create a class at runtime. It also creates a methor run and a catchall method for unknown methods But better create Objects at runtime, not classes.

    0 讨论(0)
提交回复
热议问题