8

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*

Jony Kale
  • 111
  • 1
  • 5

2 Answers2

7

You can either provide a reference to an instance to the static method:

class My {
    protected myProtected() {
        // do something
    }

    public myPublic() {
        // do something
    }

    public static myStatic(My $obj) {
        $obj->myProtected(); // can access protected/private members
        $obj->myPublic();
    }

}

$something = new My;

// A static method call:
My::myStatic($something);

// A member function call:
$something->myPublic();

As shown above, static methods can access private and protected members (properties and methods) on objects of the class they are a member of.

Alternatively you can use the singleton pattern (evaluate this option) if you only ever need one instance.

Community
  • 1
  • 1
Lukas
  • 1,409
  • 8
  • 20
7

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.

GordonM
  • 29,211
  • 15
  • 77
  • 126
  • Actually it is a quite valid pattern for factories. That is also a way to overload constructors... In some sense. Factory + various init functions. – Nux Jan 27 '21 at 19:39