在静态函数中访问公共/私有函数?

Jon*_*ale 4 php oop methods

由于您无法在静态函数中使用$ this->,您应该如何访问静态函数中的常规函数​​?

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

public final static function get()
{
    return $this->hey();
}
Run Code Online (Sandbox Code Playgroud)

这会引发错误,因为你不能在静态内使用$ this->.

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

public final static function get()
{
    return self::hey();
}
Run Code Online (Sandbox Code Playgroud)

这会引发以下错误:

Non-static method Vote::get() should not be called statically
Run Code Online (Sandbox Code Playgroud)

如何在静态方法中访问常规方法?在同一个班*

Gor*_*onM 7

静态方法只能调用类中的其他静态方法。如果要访问非静态成员,则方法本身必须是非静态的。

或者,您可以将对象实例传入静态方法并访问其成员。由于静态方法与您感兴趣的静态成员在同一个类中声明,因此它应该仍然有效,因为可见性在 PHP 中是如何工作的

class Foo {

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

    static public function baz (Foo $quux) {
        return $quux -> bar ();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是请注意,仅仅因为您可以这样做,您是否应该这样做是值得怀疑的。这种代码打破了良好的面向对象编程习惯。


Luk*_*kas 6

您可以向静态方法提供对实例的引用:

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();
Run Code Online (Sandbox Code Playgroud)

如上所示,静态方法可以访问它们所属的类的对象上的私有成员和受保护成员(属性和方法).

或者,如果您只需要一个实例,则可以使用单例模式(评估此选项).