使用trait绑定动态创建类 [英] Dynamicly creating class with trait binding

查看:226
本文介绍了使用trait绑定动态创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



因此,我创建了一些traits来使用,例如:tItem_Epic,我想要使用我的项目中的traits,并且对于多个inheriance我想使用traits。 tItem_Weapon,Item_Driver



当我为Sword创建新类时,我认为我可以使用eval创建类:

 <?php 
function new_item_class($ type)
{
eval('class Item _'。ucfirst($ type)。'extends Item_Driver { use tItem_Epic,tItem_Weapon;}');
}
?>

这是一个例子。还有一些参数改变了eval的过程(如:项目质量等)。



这是否会减慢进度?或者我应该为每个项目类型创建一个文件,并在需要时调用它们?

解决方案

您可以生成磁盘上的文件,这可能是IDE的一个好处,因为他们可以解析那些



对于PHP来说, eval 之间没有太大的区别)和 include (磁盘上的文件示例)。



我个人更喜欢文件,因为它比那些魔法类更直接。我不会寻找性能的原因来决定。你谈论的那种表演是短视的,因为它没有定义你谈论的是什么样的表演,特别是因为你还没有陷入瓶颈。


I want to make use of traits in my project, and for multiple inheriance I want to use traits.

So I created some traits to use eg: tItem_Epic, tItem_Weapon, Item_Driver

When I create new class for Sword, I thought I could use eval to create class:

<?php
function new_item_class($type)
{
    eval('class Item_'.ucfirst($type).' extends Item_Driver { use tItem_Epic, tItem_Weapon; }');
}
?>

This is an example. There are some more parameters that change the course of eval (like: item quality, etc.).

Does this slow down the progress? Or should I create a file for every item type and call them when needed? which one will be faster?

解决方案

You could generate the files on disk which could be a benefit with IDEs as they can parse those files as well and it's less magic.

For PHP there is not much difference between eval (your code-exmaple) and include (example with files on disk). So do what pleases you I'd say.

I personally prefer files because it's more direct than those magic classes. And I would not look for "performance" reasons to decide that. The kind of performance you talk about is short-sighted as it remains undefined about which kind of performance you talk about and especially because you did not yet run into a bottleneck.

这篇关于使用trait绑定动态创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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