While creating classes, I followed OO conventions and declared all class variables before using them:
class myClass {
private $property1, $property2, ...;
public __constructor() {
$this->property1 = $this->property2 = NULL;
}
}
But I realized that PHP is scripting language and not following OO concepts strictly, so we can ‘generate’ class property dynamically:
class myClass {
public __constructor() {
$this->fields = $this->db->getFields(TABLE_NAME);
foreach($this->fields as $fld) {
$this->{$fld} = NULL;
}
}
}
Is this a good approach ?
I think dynamically generated properties would have public access by default, so that could be one disadvantage and such automation could be one advantage.
Is there any difference in terms of performance ?
You’re not encouraged to do so, but in some cases you just need to (like in ORM, which you seem to be writing). Classes should have clean interfaces (programmer needs to know what can he do with your class).
But there’s a better way of handling these cases (at least, it seems better for me). Prepare an associative array of data in your class and use
__getmethod. It can be even better for an ORM (you may implement lazy loading, etc.).