在PHP运行时动态生成类? [英] Dynamically generate classes at runtime in php?

查看:248
本文介绍了在PHP运行时动态生成类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的:

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

function __autoload($class_name)
{
  //define that instance dynamically
}

显然这不是我真正在做的,但是基本上我没有一个类的名称,并且基于该名称,我想生成具有某些属性等的类.

我尝试使用eval(),但是它使我适合私有和$ this->引用...

//编辑

好吧,很明显,我简短而甜美的这就是我想做的事"在可能提供答案的人们中引起了巨大的冲突和震惊.希望得到一个实际的答案,我会更详细.

我有一个验证框架,该框架使用我维护的网站上的代码提示.每个函数都有两个定义

function DoSomething($param, $param2){
   //code
}
function DoSomething_Validate(vInteger $param, vFloat $param2){
   //return what to do if validation fails
}

我正在为数据库中的主键添加验证器.我不想为每个表创建一个单独的类(203).所以我的计划是做类似的事情

function DoSomething_Validate(vPrimaryKey_Products $id){ }

在__autoload会生成vPrimaryKey的子类并将表参数设置为Products的地方.

现在快乐吗?

解决方案

这几乎肯定是个坏主意.

我认为您最好花费时间来创建一个脚本,该脚本将为您创建类定义,而不是尝试在运行时执行.

带有命令行签名的东西,例如:

./generate_classes_from_db <host> <database> [tables] [output dir]

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($class_name)
{
  //define that instance dynamically
}

Obviously this isn't what I'm actually doing, but basically I have unknown names for a class and based on the name, I want to generate the class with certain properties etc.

I've tried using eval() but it is giving me fits over private and $this-> references...

//edit

Ok, obviously my short and sweet "here's what I want to do" caused massive strife and consternation amongst those who may be able to provide answers. In the hope of getting an actual answer I'll be more detailed.

I have a validation framework using code hints on the site I maintain. Each function has two definitions

function DoSomething($param, $param2){
   //code
}
function DoSomething_Validate(vInteger $param, vFloat $param2){
   //return what to do if validation fails
}

I'm looking to add a validator for primary keys in my database. I don't want to create a separate class for EVERY table (203). So my plan was to do something like

function DoSomething_Validate(vPrimaryKey_Products $id){ }

Where the __autoload would generate a subclass of vPrimaryKey and set the table parameter to Products.

Happy now?

解决方案

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]

这篇关于在PHP运行时动态生成类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆