Calling a public, static function in an abstract class
Asked Answered
N

3

20

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.

Navigator answered 29/4, 2015 at 14:34 Comment(1)
Yes a static method is not stored in the same place as the class's instance(instance != declaration). This will give you clues: #17407703Spontoon
W
11

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

Wince answered 29/4, 2015 at 14:49 Comment(2)
I'm interested to know (at a low-level) how this is implemented in the PHP runtime - any insight? And by internal state you mean internal state of the abstract class?Navigator
By internal state i mean just internal state. Static methods should not save anything internally, thus changing internal state. E.g. just get an input, do things and output the result that will be the same with same input. You can just threat static methods like general PHP functions.Wince
D
6

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.

Distributive answered 29/4, 2015 at 14:51 Comment(0)
H
0
abstract class ScopeFactory
{
    public static function doStuff()
    {
        static::otherStuff();
    }

    abstract public static function otherStuff();
}
Class Factory Extends ScopeFactory{

    static function otherStuff(){
    echo "hello world";
    }
}
Factory :: otherStuff();

in this there is no error occurred. Output is hello world

Helicopter answered 15/6, 2023 at 13:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.