Skip to content
Advertisement

Accessing a public/private function inside a static function?

Due to the fact that you can not use $this-> inside a static functio, how are you supposed to access regular functions inside a static?

private function hey()
{
    return 'hello';
}

public final static function get()
{
    return $this->hey();
}

This throws an error, because you can’t use $this-> inside a static.

private function hey()
{
    return 'hello';
}

public final static function get()
{
    return self::hey();
}

This throws the following error:

Non-static method Vote::get() should not be called statically

How can you access regular methods inside a static method? In the same class*

Advertisement

Answer

Static methods can only invoke other static methods in a class. If you want to access a non-static member, then the method itself must be non-static.

Alternatively, you could pass in an object instance into the static method and access its members. As the static method is declared in the same class as the static members you’re interested in, it should still work because of how visibility works in PHP

class Foo {

    private function bar () {
        return get_class ($this);
    }

    static public function baz (Foo $quux) {
        return $quux -> bar ();
    }
}

Do note though, that just because you can do this, it’s questionable whether you should. This kind of code breaks good object-oriented programming practice.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement