在静态函数中访问公共/私有函数? [英] Accessing a public/private function inside a static function?
问题描述
由于您可以不能在静态函数中使用 $this->,您应该如何访问静态函数中的常规函数?
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->.
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();
}
这会引发以下错误:
Non-static method Vote::get() should not be called statically
如何访问静态方法中的常规方法?在同一个班级*
推荐答案
静态方法只能调用类中的其他静态方法.如果要访问非静态成员,则方法本身必须是非静态的.
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.
或者,您可以将对象实例传入静态方法并访问其成员.由于静态方法与您感兴趣的静态成员在同一个类中声明,由于可见性在 PHP 中的工作方式,它应该仍然有效
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.
这篇关于在静态函数中访问公共/私有函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!