Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm currently writing a class:

final class MyTestClass {
  const URL = 'http://www.example.org';
  private static $MY_ARRAY = array('...');

  // since this is not allowed
  // const MY_ARRAY = array('...');
}

So my question is whether I should make URL a private static variable, too? These values are constant and are only used in the class itself.

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

See PHP Constants Containing Arrays? . I think both are valid and also your current approach is fine. It's only important that you stick with one solution in your whole project.

Personally I think I would stay with your current solution.

share|improve this answer
add comment

I'm not quite sure that this question is on topic, however:

You have to understand what each variable definition is and what it means for the accesibility of that variable.

Say your class definition is as follows:

class MyTestClass {
  const URL = 'http://www.example.org';
  private static $MY_ARRAY = array('...');
}

And in the future you write another class that extends that class and it wants to update URL as below:

class SomeOtherClass extends MyTestClass {
  public __construct(){
    $this->URL = "http://www.someothersite.com";
  }
}

Now, if you never want URL to change, then that's fine. A better way to write MyTestClass however, would be:

class MyTestClass {
  private $URL = 'http://www.example.org';
  private $myArray = array();
}

Again however, if some class extends it, they won't be able to access the $URL var. Also, stay away from static.

share|improve this answer
    
This class will never be extended (now declared as final in the question). I just want to store a constant variable thus I took const URL, but PHP doesn't let me store arrays in there so my array variable will be declared as private static. Therefore I have to write both MyTestClass::URL and self::$myArray in the code. That's inconsitent in my opinion. –  ComFreek Jan 18 '13 at 18:43
    
Ah! I misunderstood, sorry. –  jsanc623 Jan 22 '13 at 17:25
1  
No problem! Thanks for taking time to write the answer anyway ;) –  ComFreek Jan 22 '13 at 17:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.