views:

122

answers:

3

I have an abstract "object" class that provides basic CRUD functionality along with validation, etc. Typically I would use the __autoload($name) magic function to load a class that would exist in its own file, named the same as the class I wish to lazy load. The code would look something like this, which as you can imagine becomes quite repetitive.

final class bicycle extends object {
    public function __construct($id=null) {
      parent::__construct($id, __CLASS__);
    }
    public function __toString() {
      return($this->name);
    }
}

My question is whether or not I can somehow dynamically generate these classes on the fly so I don't have to create the same functionality over and over - thus reducing overhead and design time. Does PHP5 even support this or am I simply overestimating the power of OO PHP?

Thanks!

A: 
TML
The child class passes it's name to the parent's constructor to be run through a series of tests and eventually, using a naming system, it determines the table name (if exists) and sort of provides an automated rails-esque scaffold environment. This saves me a lot of time at work as I have to come up with basic small apps to appease some manager. :)
Kyle J. Dye
+5  A: 

Hi,

Instead of copy-pasting this, why don't you just put the code of the __construct and __toString methods in the definition of your object class ?

Something like this should do :

class object {
    public function __construct($id = null) {
        $this->name = get_class($this);
    }
    public function __toString() {
      return($this->name);
    }
    protected $name;
}

final class bicycle extends object {

}

And, calling it :

$a = new bicycle();
var_dump($a);

You get :

object(bicycle)[1]
  protected 'name' => string 'bicycle' (length=7)

Which means an instance of class bicycle, with the name property at the right value.

No need to copy-paste any code -- except for the definition of the bicycle class itself.


As a sidenote, if you really want to generate a class dynamically, you can probably use something like this :

$code = 'final class bicycle extends object {}';
eval($code);

You just have to construct the $code variable dynamically.

But I would strongly advise against this :

  • you will not have code assist in your IDE, as it cannot see the class
  • you will not have phpdoc for your class (same reason)
  • there is always the "eval is evil" stuff -- and that's quite true, at least in this situation.
  • using "new bicycle" without having declared the class feels wrong !
  • there's gotta be some performance implication with the use of eval

Declaring a new class is not such a pain, and I would definitly prefer copy-pasting-modifying a few line than use anything like this.

Pascal MARTIN
A: 

This functionality does not exist in PHP5. It may be available in PHP6, but since there is no package for ubuntu yet I will not proceed.

Kyle J. Dye