PHP对象坏了,$这是未定义的

The code:

<?php

class My_Test{

    public $exists = 'yah';

    public function test(){
            return $this->exists;
    }

}

$test = new My_Test;
echo $test->test();

produces the following error intermittently (every other page request on average) on two servers:

( ! ) Notice: Trying to get property of non-object in test.php on line 8
Call Stack
#   Time    Memory  Function    Location
1   0.0003  636392  {main}( )   ../test.php:0
2   0.0003  636840  My_Test->test( )    ../test.php:14

where line 10 is `return $this->exists;

Please note this is not an untested example, it is the full code that produces the error. I'm aware the code is valid but it doesn't work in two environments.

I'm really not sure why! One server is running PHP 5.3.3 (fedora), the other PHP 5.3.2 (ubuntu). I've tried rebooting the servers too. They don't share anything, although they are on the same network.

Anyone got any tips for debugging?

As people before stated the code looks fine and should not cause any errors.

Therefore I guess it is related to an error of the php engine itself:

How did you install PHP?

  • Did you compile the sourcecode yourself? Have ./configure or make logged any warnings or error messages while executing?
  • Have you installed PHP by use of a package manager? (I guess everything should be fine then).

How did you configure PHP?

  • Have you made any changes to php.ini like changing memory limit, paths, etc. ?
  • Have you installed any extension that might cause issues? My experience says often opcode caches (e.g. APC) can cause errors that cannot be easily explained. Also debuggers or other extensions may cause interferences.

Do you have any (additional) error messages in your HTTP-Daemon-Log?

  • Sometimes additional errors can be found in the error.log file in case the server is configured to do so (e.g. unexpected termination of script or similar).

There's nothing wrong with your test code. It runs without issue on PHP 5.3.3. You've probably lost the cause of the issue when converting your "real" code into test code to post on here.

The code appears to work as is, but I've never seen an object instantiated without the parens.

$test = new My_Test;

// Should be

$test = new My_Test();

You could also implement some logging:

public function test()
{
    // Can edit this to use instanceof or getclass for further testing
    if (!is_object($this)) {
        error_log(serialize($this));
    }

    return $this->exists;
}