2

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
Fluffy
  • 27,504
  • 41
  • 151
  • 234
  • re your comment on my post, you're absolutely right. As I had mentioned on the bottom I'm a tad coffee deprived. Also was under the impression my test box here at work was a 4.x, but I guess it has since been upgraded. (lucky for me all development resides in-house anyways). Also, it's not that you can't do the same in PHP, just can't specifically decorate the methods as static. Good PHP4 Demo: http://abing.gotdns.com/posts/2006/php4-tricks-the-singleton-pattern-part-i/ – Brad Christie Dec 01 '10 at 14:48

1 Answers1

3

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

ajreal
  • 46,720
  • 11
  • 89
  • 119
  • Touche on catching the `$this` usage. – Brad Christie Dec 01 '10 at 14:39
  • I don't think this code is calling it statically. call_user_func_array is used to call the method on an instance, not the class. – Jani Hartikainen Dec 01 '10 at 14:39
  • @Jani Hartikainen - that's why it does not work, you can follow the example listed above (provided you have php 4) – ajreal Dec 01 '10 at 14:44
  • 1
    @ajreal, thanks a lot! this helped me to solve an issue I was stuck on for a couple of days, btw making the code work is a matter of merely changing `array($GLOBALS['instance'], 'add')` to `array(&$GLOBALS['instance'], 'add')` – Fluffy Dec 01 '10 at 14:48
  • Oh been too long since PHP 4 for me it seems... :D – Jani Hartikainen Dec 01 '10 at 15:02
  • @Jani Hartikainen - `2004-07-13 Zend Engine II with a new object model` - http://en.wikipedia.org/wiki/PHP , it will surprise me if someone out there still ... using PHP 3 – ajreal Dec 01 '10 at 15:12