3

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 ?

1

4 Answers 4

5

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 __get method. It can be even better for an ORM (you may implement lazy loading, etc.).

Sign up to request clarification or add additional context in comments.

2 Comments

but in some cases you just need to (like in ORM - it's definitely stupid ORM, where you need to do it. And this feature was created for freaks. __get and __set looks like properties implementation from C#, and could be very useful, but they can't be described in interface (in PHP).
ok, but I think, in case we want to assign all properties in constructor, __get and __set methods are very costly in terms of time.
2

If you're writing code (library) that many users should use, it would be better to be strict in the definition of your API. so that there would be less mess when implementing it. but if you're using it for a single case it wouldn't be so bad, in fact it could provide much flexibility.

Comments

1

This depends on your situation. This is a common practice when you have have data containers that are mapped directly to tables (or some other structure). Most commonly used in ORMs because the columns are determined at run time and you don't need to define a container class for each of your tables.

Comments

1

It all depends on how you want to make use of those publicly available variables. For example in frameworks like Symfony make very good use of them. all dynamic class variable are can be made available outside the class in templates and such.

So it can be a good practice if you are creative with them

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.