1

Is this a pitfall that some have encountered? I have only recently discovered the notion of defining a constant to use globally but find myself attempting to define away each and every repetitive block of code (no matter how long).

Can I get two major reasons when to avoid using constants and one supportive reason/example illustrating great use?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • You turn *blocks of code* into constants...? How do you do that? – deceze Mar 13 '14 at 07:43
  • @deceze even though you ask I think know. For example, the favicon, metadata, other head elements which never change can all be wrapped in a single set of quotations and echo'd as a constant deemed TOP –  Mar 13 '14 at 08:00

1 Answers1

1

The reason not to use constants - Having global data is typically considered bad practice. Since PHP has the ability to be object oriented, most well written software takes advantage of it. Here is a pretty good explanation without getting too lengthy about encapsulation and abstraction.

The reasons I consider using them, typically for things that are reusable, that I would like to change all at once. an example i can think of is contact information. It's usually in the footer, sometimes the header and typically on a contact page. If I want to reuse a template I can just change the information in one spot and effectively update it on the entire site. Usually the database credentials live in the same file. I'm not saying this is the best practice, but it's convenient to only have to make changes to one file for global changes to a website.

That's just my 2 cents.

Community
  • 1
  • 1
Bryan
  • 3,449
  • 1
  • 19
  • 23
  • Not bad as for why to, but when should you not? I keep getting this feeling that I'm trying to hard to remove the code from my body and worry it will impact performance or soon enough debug-ability . Can this eventually become an issue? –  Mar 13 '14 at 08:04
  • It depends who you ask, people who are OOP all the way say never use them. My advice would be don't use them arbitrarily, if a variable can be encapsulated and do the same job, use a variable. Otherwise trying to move around the code to see what the value you're working with can get old. – Bryan Mar 13 '14 at 08:09
  • After reading your comment above. I would be using includes instead of constants for blocks of html. – Bryan Mar 13 '14 at 08:12