0

I have a static language class that pulls key-value pairs from a JSON file and places them in a property of this class. This happens before any other code/classes are run.

This class needs to be accessed by about half of all other classes and their methods.

In order to stay away from using new Language(); within every method/class constructor, I'm currently using something similar to skwee's answer in which he posts:

class Context {
public $application;
public $logger;
}
========
$context = new Context();
$context->application = new Application();
$context->logger = new Logger(...);
doFoo($context);
========
function doFoo(Context $context) {
    $context->application->doStuff();
    $context->logger->logThings();
}

However this has a severe annoyance when it comes to method calls within other classes, namely exceptions.

class A {
  public function call(Language $lang) {
    throw new Custom_Exception($error, $lang);
  }
}

class Custom_Exception extends Exception {
  public function __construct($error, Language $lang) {
    parent::__construct($lang->vars->preError . $error);
  }
}

Just to be able to use the static language property, the Language object needs to be passed twice, possibly three times in a few situations. I'm looking for a better/more efficient way.

Community
  • 1
  • 1
Chris Bornhoft
  • 4,195
  • 4
  • 37
  • 55
  • If you only use one `Language` object you could use a singleton design pattern and then use it in you other classes like: `Language::$property`. http://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5 – Cyclonecode Dec 16 '13 at 08:42
  • @KristerAndersson Thanks but I might as well use a static class in that case. I'm trying to find an elegant solution using what I have built already. – Chris Bornhoft Dec 16 '13 at 10:57
  • But if you have a static class why do you have to send the `Language` object to the constructor in the first place? Why not just access the static property directly from within the constructor? – Cyclonecode Dec 16 '13 at 11:00
  • @KristerAndersson Language is not a static class. I'm saying I would use a static class over Singleton if I were given the choice between the two. – Chris Bornhoft Dec 16 '13 at 11:04
  • But still if you declare `preError` as `public static $preError` inside your class then you would be able to do `Language::$preError` from within the constructor of your second class. – Cyclonecode Dec 16 '13 at 11:05
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/43254/discussion-between-chris-bornhoft-and-krister-andersson) – Chris Bornhoft Dec 16 '13 at 11:45

0 Answers0