1

I know I can generate a class at runtime by executing

$obj = (object)array('foo' => 'bar');+

this way I can use

echo $obj->foo; //bar

What if want to make $obj inherits from an existing class?

What I wanna achive: I'm forking paris project on github (https://github.com/balanza/paris). It's an active record class. I wonder I need to declare a class for every object, even if it's empty:

class User extends Model{}

I guess I might use dynamic object to avoid this boring stuff.

hakre
  • 193,403
  • 52
  • 435
  • 836
balanza
  • 1,059
  • 1
  • 12
  • 34
  • 1
    So you want a totally obscure way to create an object which extends from the class because it's "boring" to define the class? Besides if your extension class is empty what's wrong with $obj = new Model();? Or is that "boring" too? – Cfreak Feb 07 '11 at 17:51
  • 1
    `(object)array()` does not "generate a class at runtime", it creates an **object**. That's an important difference. – deceze Feb 08 '11 at 02:44

4 Answers4

2

You could always do eval('class User extends Model{}') but is not a good idea. Really, you should just create the class in a file, then opcode caching will work properly, it can be version tracked, etc etc.

tl;dr: Define the model class, it is the Right Thing To Do™.

shadowhand
  • 3,202
  • 19
  • 23
1

If there is really no other way for you to do it, you can create a "dynamic" inheritance with my Dynherit class. It creates the inheritance you want but from files and only with classes you didnt already loaded.

Download v0.62 : http://optimisationphp.komrod.com/source/sha/test/dynamic_inheritance_01/dynherit_v0.62.zip

GitHub link : https://github.com/Komrod/Dynherit

Komrod
  • 11
  • 1
0

Strictly to your question, the only way I can see it possible is by using Runkit, which let's you re-declare classes on the fly. Not sure how portable that solution is.

mhitza
  • 5,709
  • 2
  • 29
  • 52
0

You can use a Prototype design pattern to clone an object, then you can add everything you need in cloned one

Ilya Kolesnikov
  • 623
  • 8
  • 17