doushajian2018 2016-05-03 18:25
浏览 47

PHP:如何在运行时创建和注册类

Is there any official/recommended way to declare/define/register a new class at runtime in PHP?

What I basically want to do is generating Classes based on the definition stored in a database, both properties and methods.

I have found some article/threads, but all of them are actually old, so I was wondering if it exists some elegant/efficient way to do it. My surprise is that there is no so much information about this as I thought.

Is it so bad? As far as I know, PHP always saves the class definition in memory so I don't see any problem in declaring the class at runtime as it's basically the same result, but maybe I'm wrong.

I think is not relevant right now, but I'm working with Laravel in this project.

Thanks!

  • 写回答

1条回答 默认 最新

  • dongyou1926 2016-05-03 18:35
    关注

    Yes.

    <?php
    
    $foobar = "foobar";
    
    eval("class $foobar {" .
            "function __construct(\$i) {" .
                    "echo \"Dark magic ritual complete. \$i virgins sacrificed to satan.\"; " .
            "}" . 
    " }");
    
    $evil = new $foobar(5);
    
    
    echo "<br /><br />";
    
    var_dump($evil);
    

    Produces:

    Dark magic ritual complete. 5 virgins sacrificed to satan.

    object(foobar)#1 (0) { }

    I'm not going to lecture you on semantics, but this is a terribly bad idea and you should reconsider using classes to facilitate what the database records need. A class by itself is not special, but using a class to handle a database entry is perfectly acceptable.

    评论

报告相同问题?

悬赏问题

  • ¥15 需要手写数字信号处理Dsp三个简单题 不用太复杂
  • ¥15 数字信号处理考试111
  • ¥100 关于#audobe audition#的问题,如何解决?
  • ¥15 allegro17.2生成bom表是空白的
  • ¥15 请问一下怎么打通CAN通讯
  • ¥20 如何在 rocky9.4 部署 CDH6.3.2?
  • ¥35 navicat将excel中的数据导入mysql出错
  • ¥15 rt-thread线程切换的问题
  • ¥15 高通uboot 打印ubi init err 22
  • ¥15 R语言中lasso回归报错