3

I once heard it's good to have one class with all your application constants so that you have only one location with all your constants.

I Tried to do it this way:

class constants{
    define("EH_MAILER",1);
}

and

 class constants{
         const EH_MAILER =1;
 }

But both ways it doesn't work. Any suggestions?

2
  • Where did you hear that? I think it's best to couple the constant with where it will be used. Also, what is EH in your example? I think that constant deserves a better name. Commented Mar 25, 2009 at 20:19
  • If you're doing a more procedural style application, I could see an argument for an include full of define()s, but, if you're working with OO, putting all the constants in a single class makes no sense. They belong with the class that they're (most) relevant to. Commented Mar 25, 2009 at 20:42

2 Answers 2

18

In the current version of PHP this is the way to do it:

class constants
{
   const EH_MAILER = 1;
}

$mailer = constants::EH_MAILER

http://www.php.net/manual/en/language.oop5.constants.php


Starting with PHP 5.3 there's better way to do it. Namespaces.

consts.php

<?php
namespace constants
const EH_MAILER = 1

...

other.php

<?php
include_once(consts.php)

$mailer = \constants\EH_MAILER
Sign up to request clarification or add additional context in comments.

4 Comments

This is the way I would suggest doing it.
This is the solution i was looking for. Without the namespaces of course! Tnx
Wouldn't that be \constants\EH_MAILER, or at the very least constants\EH_MAILER?
@Adam: You're right.There's been a lot of discussion about which will be namespace separator, in early versions it was :: (like in C++)
0

What php version are you using?

See php's page for class constants

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.