Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a public, static function in an abstract class

I guess this question is geared more towards the language-geeks. I have the following class:

<?php  
abstract class ScopeFactory
{
    public static function doStuff()
    {

    }
}

Now, I'm able to call this function, like so:

ScopeFactory::doStuff()

And this works happily. I've always coded under the impression that abstract classes could not be used directly - and they have to be implemented by a concrete class in order to be callable.

My impression of static is that it does not require an instance to be callable.

Could someone explain to me why this is legal, and if it should be? I'm curious about the finer details.

like image 259
Danny Kopping Avatar asked Apr 29 '15 14:04

Danny Kopping


2 Answers

Static methods in OOP do not change internal state, therefore you can call static methods from an abstract class.

like image 51
Artem L Avatar answered Oct 12 '22 12:10

Artem L


I would be surprised if this wouldn't be allowed. Abstract class assumes you cannot instantiate it. As static methods don't need a class instance, you can happily use them.

Looking deeper, you could create an abstract static method and call it from your non-abstract method:

abstract class ScopeFactory
{
    public static function doStuff()
    {
        static::otherStuff();
    }

    abstract public static function otherStuff();
}

PHP will give you a fatal error saying you cannot call an abstract method. But also it'll give you a E_STRICT warning saying you shouldn't create abstract static methods.

like image 45
astax Avatar answered Oct 12 '22 12:10

astax