Overriding methods in PHP

Overriding and overloading messages in PHP can be a little weird! There are things that will work ant stuff which will not. For example, this method overriding will work:

<?php

class A
{
    function test(string $s)
    {
    	echo "$s";
    }
}

class B extends A
{
    // overridden - still maintaining contravariance for parameters and covariance for return
    function test(?string $b): ?int // test($b) | test($b) would also work
    {
    	return null;
    }
}

Result for 8.1.9, 7.3.33, 7.2.34, 7.1.33: (no error)

Result for 5.6.40:

Parse error: syntax error, unexpected ':', expecting ';' or '{' in /home/user/scripts/code.php on line 13

However, we are not able to omit method variable. We can set it defaults to null, we can use ? Operator to make it optional. We could commit string type casting (but we are not able to change to something else like int or bool).

This example will not work:

<?php

class A
{
    function test(string $s)
    {
    	echo "$s";
    }
}

class B extends A
{
    // overridden - still maintaining contravariance for parameters and covariance for return
    function test() // test(int $s) will also not work as we change type casting
    {
    	return null;
    }
}

Overloading methods in PHP

Overloading method is not possible using typical methods from languages such as Java or C++. To overload methods in PHP, we are forced to use __call magic method.

0
Would love your thoughts, please comment.x
()
x