tags:

views:

89

answers:

1

We have very strange errors occasionally popping up in our php logs: Trying to get property of non-object.

This exact error seems to be caused by the access to the member $shortName in the following if statement:

class MyLocaleWrapper {
    …
    protected static $system = NULL;
    public static function getSystemLocale() {
        if (self::$system === NULL) {
            self::$system = new self();
            self::$system->rfcName = SYSTEM_LOCALE_RFCNAME;
            self::$system->shortName = strtolower(Locale::getRegion($rfcName));
            if (self::$system->shortName == '') {
                self::$system->shortName = strtolower($rfcName);
            }
            …

if I dump self::$system into a log file, I see that it is NULL - right after being constructed with the keyword new.

The most interesting part is that this file is included in each and every request to our page, so it gets executed ~ 10 times per second. But occasionally it just fails without anyone touching the code (or even the server).

Has anyone else ever experienced such behavior in PHP?

A: 

Try the singleton approach:

class MyLocaleWrapper {
    …
    private static $system = NULL;//set it to private, and instead of accessing it as $this->system, access it with self::getInstance() or parent::getInstance() if your trying to get the parent instance
    public static function getInstance() {
        if (!(self::$system instanceof self)){
            self::$system = new self();
        }
        return self::$system;
    }
    final private function __construct() { }// Do not allow an explicit call of the constructor: $v = new Singleton();
    final private function __clone() { }// Do not allow the clone operation: $x = clone $v;
    public static function getSystemLocale() {
        $self = self::getInstance();
        log($self);//dump the value into a file with you function
…

and see what the value of $self is

Your problem seems to spawn from something overwriting or just because your not setting the $system variable

with the singleton approach you ensure that the instance has only been set once and that nothing is overwriting it.

p.s. what does the file actually do?

YuriKolovsky
I can hardly change the production server like that. But I have print_r()ed the value into a file and `$this` was `NULL`.
soulmerge
usually you have a development server and a production server, but I have experienced working with production code directly as well, so ill edit my answer.
YuriKolovsky