Code not working in PHP 4
I have a PHP script which works fine in PHP 5, but not in PHP 4. I've made a small test case for you to demonstrate (disclaimer: I know that the below code could be written much better, but it's not an actually used piece, rather the one to demonstrate what I'm talking about):
class Messenger {
var $messages = '';
function add($message) {
$this->messages .= "$message\n";
开发者_运维问答 }
}
function add($m) {
if (! isset($GLOBALS['instance'])) $GLOBALS['instance'] = new Messenger();
call_user_func_array(array($GLOBALS['instance'], 'add'), array($m));
}
add("One");
add("Two");
add("Three");
var_dump($GLOBALS['instance']->messages);
Under PHP 5 the messages
property contains all 3 messages, under PHP 4 it is empty. Why?
In PHP 4, $this
does not seems to be work the same way as PHP 5 does.
The $this pseudo-variable is not usually defined if the method in which it is hosted is called statically. This is not, however, a strict rule: $this is defined if a method is called statically from within another object. In this case, the value of $this is that of the calling object. This is illustrated in the following example:
example : http://www.php.net/manual/en/keyword.class.php
精彩评论