Accessing a public/private function inside a static function?

10,854

Solution 1

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.

Solution 2

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.

Share:
10,854
Jony Kale
Author by

Jony Kale

Updated on June 13, 2022

Comments

  • Jony Kale
    Jony Kale almost 2 years

    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*

  • Nux
    Nux over 3 years
    Actually it is a quite valid pattern for factories. That is also a way to overload constructors... In some sense. Factory + various init functions.