douturan1807 2010-07-08 21:14
浏览 16
已采纳

是否有一个__get魔术方法等效于实例化类?

Looking to see if there is any way to implement the kind of functionality of the __get() magic method, but when trying to instantiate a new class.

My goal is to have

$foo = new Cat();

Ultimately result in the creation of a generic object, i.e.

new Mammal('Cat');

Such that $foo would be an instance of the class Mammal, with the called class name ('Cat') passed as an argument to Mammal's constructor.


Note: The end game I have in mind, for those familiar with Lithium or CakePHP, is to avoid having to define a whole bunch of classes for each different database table. If I did, most would simply be empty, the basic CRUD operations being all that is necessary. Plus, all those includes and class definitions can't be great for overhead. My idea would be to use a single "Model" class to handle most of the generic functions, and I could always create subclasses if I needed more advanced functionality for a specific database table.

  • 写回答

4条回答 默认 最新

  • douchongzhang9267 2010-07-08 21:22
    关注

    I don't think there is any straightforward non-hacky way to achieve what you want with the class instantiation mechanism.

    I would recommend using a factory:

    $tableFactory->createTable('Cat');
    

    Which would then work out what needs to be done behind the scenes. This also has the benefit of if you ever decide Cat requires its own class, you can simply modify the factory and you may not need to modify the code that is using it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 能不能通过蓝牙将传感器数据传送到手机上
  • ¥20 python和数据科学实验项目
  • ¥15 根据时间在调用出列表
  • ¥15 FastReport.community 编辑,table只显示“每页”最顶部和底部横线
  • ¥15 R 包chipseeker 安装失败
  • ¥15 Veeam Backup & Replication 9.5 还原问题
  • ¥15 vue-print-nb
  • ¥15 winfrom的datagridview下拉框变成了黑色,渲染不成功
  • ¥20 利用ntfy实现短信推送
  • ¥30 如何用VBA代码写抽取TRIBON M3数据库的模型信息