views:

80

answers:

1

Here is the simple php code

<?
abstract class A{
abstract public function a($x);
}
class B extends A{
public function a($x)
{
echo $x;
}
}

$q = new B;
$q->a(10);
?>

which gives: PHP Fatal error: Cannot call abstract method A::a()

but changing the name of the function to something else than "a" works.

So what is really happening with the call to a(10) ? I don't see the logic here.

+3  A: 

You got a pretty obvious problem. Since you don't have a __construct() method, the abstract public function a(); is your constructor (php 4). Your fatal error fires when instantiating the B class, and not when calling method a() on the instance of B class.

If you change the name of your method a() in something else, all works as intended!

Example that works:

<?php
abstract class A
{
    abstract public function test($x);
}

class B extends A
{
    public function test($x)
    {
        echo $x;
    }
}

$q = new B();
$q->test(10);
?>
Bogdan Constantinescu
An alternative is to add a `__construct` to `A`.
Artefacto
Of course :) +1
Bogdan Constantinescu
@Artefacto triggers `Strict Standards: Redefining already defined constructor for class A`. At least if you keep function `a()` as well. I'd say this is a great example where backwards compatibility is actually more like a bug than anything else.
Gordon
@Gordon I can't reproduce that. See http://codepad.viper-7.com/IgdKFi I added a call that generated a strict error to prove it's on.
Artefacto
@Artefacto see http://codepad.viper-7.com/kDRSiq - remove either `a()` or `__construct` and there will be no more strict error. Ugly.
Gordon
@Gordon Apparently it's the order of declaration that determines whether there's an error or not. Not pretty.
Artefacto
@Artefacto Nope, the strict error will always be raised. The order only affects for which the error will be raised, e.g. when I put a() first, it will complain about __construct and vice versa. I've copied your codepad example into Zend Studio running PHP5.3.2 and added the error_reporting on top and it will raise too.
Gordon
@Gordon I think we're getting somewhere :p I can indeed confirm the snippet in http://codepad.viper-7.com/IgdKFi raises an error on PHP 5.3.2, but not on trunk and apparently not on the development version of 5.3 (5.3.3RC3-dev, which viper7 runs).
Artefacto
@Artefacto interesting. I can confirm that the error does not occur on 5.3 and 5.2.10 on Windows either.
Gordon