Question

The static keyword was introduced in PHP5, which kinda makes one come to the conclusion that PHP4 didn't support static methods or variables. And yet when I run the following code on PHP 4.4.9 it works without the constructor ever being called.

<?php
class a {
    function a() {
        echo "CONSTRUCTOR CALLED\r\n";
    }

    function b($var) {
        return $var . 'x';
    }
}

print_r(array_map(array('a', 'b'), array('a', 'b')));

You can play around with the code with this PHP "fiddle":

http://sandbox.onlinephpfunctions.com/code/1d6882a8264620a0165d7345791f8680586a869e

Any ideas as to how this is working?

Was it helpful?

Solution

All the static keyword does is tell PHP that a function should be called statically. In actual fact, even the latest versions will let you call any function statically if you want, as this online demo with your code in multiple PHP versions shows.

If you turn error reporting to the max, as in this demo you will see that newer versions of PHP give an E_STRICT message that you're using a function statically that hasn't been declared as such, but otherwise run the code exactly as before.

All that's needed to make a static function call is ::, and that was present and correct in PHP 4. It's really the non-static methods that were tidied up in PHP 5, and further in 5.3

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top