Reputation: 1724
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!
Upvotes: 0
Views: 644
Reputation: 1724
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.
Upvotes: 0
Reputation: 401002
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 :
new bicycle
" without having declared the class feels wrong !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.
Upvotes: 6
Reputation: 12966
Well, for __toString, you just put it in the parent class. Example follows:
class BaseObject {
public function __toString() {
return $this->name;
}
}
class bicycle extends BaseObject {
}
$b = new bicycle();
$b->name = 'foo';
echo $b;
I'm not exactly sure what you're trying to accomplish with overriding the constructor to pass in CLASS.
Upvotes: 0