Forum Moderators: coopster

Message Too Old, No Replies

Objects and Globals

         

neophyte

12:16 pm on Sep 22, 2014 (gmt 0)

10+ Year Member



Hello All -

I'm learning OOP (from many years of procedural) and have a quick question regarding the use of using global vars in objects.

In many of my previous projects I've written a config file that sets a number of basic project properties. One of these properties is "\n". As all my content (html tags, head tags, body tags, etc) were script-generated, I always separated each tag (and each line of tag-content) with new lines so that - in code view - it was easier to read/review.

So, in my config file, I'd set a var like so: $snl = "\n";

Then I'd declare $snl as a global in any function that needed it and then simply typed $snl as required.

I've tested this in a few objects and, as long I declared "global $snl" in the constructor, it works fine.

But, I've also read on the web that this technique of using globals within objects is frowned upon as - in the words of one poster - it goes against the purpose of a self-contained object.

So, since I'm just learning this stuff, is this poster correct? If so, is there a better way to feed these small bit's of config data to various objects without having to pass them to the constructor upon instantiation, or type them verbatim directly into each object?

Should I (could I?) use a config object for this kind of data and then pass that object to other objects that need it?

I'm not trying to over complicate the issue, but I'm very keen on learning this correctly so all advice and "best practice" illumination on this subject would be greatly appreciated.

bhukkel

6:59 pm on Sep 22, 2014 (gmt 0)

10+ Year Member



The basic idea of OOP is to create simple reusable objects by hiding the complexity of the data and provide simple messages to interact with the outside world. So i don't think global variables fit into this idea.

Perhaps you need to redesign your classes so they don't need any or less globals. Why write html code from different classes? Separate your logic from presentation! If you teach yourself a new programming way look at MVC design pattern.

If you really want to use globals my personal opinion is to create a global object.