Php,方法范围界定问题(对某人公开,对其他人私有,C++朋友一样)


Php, problems with method scoping (public for someone, private for others, C++ friend alike)

两个类:

class main()
{
 public function doAjob()
 {
  helperClass::clean();
 }
}
class helperClass()
{
 public function add() { }
 public function remove() { }
 public function clean() { } // **this should be only allowed from main::doAjob() !!!**
}

这些类的用户可以使用doAjob(),add(),remove()方法,但不能使用clean()。这只允许用于主类。它在C++里有点朋友。如何躲避?最好的办法是甚至没有通过代码竞争看到它。

你不能在 PHP 中这样做。没有"朋友"类的概念。如果希望方法在类外部可访问,则必须public

好吧,阅读本文的人可能会有其他选择:将它们公开,您可以backtrace()函数调用,并确定调用来自何处。但是,这使得应用程序非常慢,因此最好添加一种机制来启用/禁用。