-4

base class:

abstract class Challenge
{
    abstract **static** public function getName();
}

now two classes from it:

class ChallengeType1 extends Challenge
{
    public **static** function getName()
    {
        return 'Swimming';
    }
}

class ChallengeType2 extends Challenge
{
    public **static** function getName()
    {
        return 'Climbing';
    }
}

as you all might know, we can't use static, but it would be reasonable. So I can't do like that: for example, I have the classname, so I want to know it's name: ChallengeType2::getName(); - it will fail! First I should construct the object - looks unnecessary (not to mention, what it this class have very complex initialization?)

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
user893856
  • 1,039
  • 3
  • 15
  • 21
  • The code you've posted works fine from where I'm standing. Well, once the asterisks are removed. – femtoRgon Nov 28 '12 at 22:24
  • Please don't decorate your code with things like `**static**`. The code you post should be *valid* code. – user229044 Nov 28 '12 at 22:24
  • What makes you think this doesn't work? What error are you getting? Give us enough information to help you, and you'll get better results and fewer downvotes. – user229044 Nov 28 '12 at 22:25
  • oh, if I add the static keyword, php 5.4 will say: Static function Challenge::getName() should not be abstract in – user893856 Nov 28 '12 at 22:27
  • Your code looks fine - Are you running this from command-line or via a dev-tool (i.e. Eclipse, etc)? And are you sure you are using 5.4 ? – David Farrell Nov 28 '12 at 22:32
  • yes. This is 5.4.6. And for the line "abstract static public function getName();" it will say "Strict Standards: Static function Challenge::getName() should not be abstract in sklsdkf" – user893856 Nov 28 '12 at 22:35
  • I was mistaken, it actually didn't work in my IDE but it showed me an empty `stdout` which is what I expected - Once I checked my `stderr` console, the error you posted was there. I've researched it and presented a solution below. – David Farrell Nov 29 '12 at 01:30
  • @user893856, please have a look at my answer below and let me know if my solution works for you. Thank you. – David Farrell Nov 29 '12 at 06:53

1 Answers1

1

Turns out you cannot have static abstract methods on an abstract class. See here:

Why does PHP 5.2+ disallow abstract static class methods?

But you can declare an interface to require a static method.

Here is an example that compiles:

Working Example

<?php
interface IChallenge
{
    static function getName();
}

abstract class Challenge implements IChallenge
{

}

class ChallengeType1 extends Challenge
{
    public static function getName()
    {
        return 'Swimming';
    }
}

class ChallengeType2 extends Challenge
{
    public static function getName()
    {
        return 'Climbing';
    }
}
Community
  • 1
  • 1
David Farrell
  • 3,492
  • 2
  • 15
  • 11