使用私有类函数/变量的PHP静态方法

How*_*opa 6 php methods static

如果我在类中编写一个公共静态方法,即......

public static function get_info($type){
        switch($type){
            case'title':
                self::get_title(); 
                break;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我必须把我的get_title()函数写成public ...

public static function get_title(){
        return 'Title';
    }
Run Code Online (Sandbox Code Playgroud)

否则我收到错误:

Call to private method Page::get_title()
Run Code Online (Sandbox Code Playgroud)

这让我觉得这个功能get_info()本质上是多余的.我希望能够从我的类中的静态方法调用私有方法进行验证.这不可能吗?

PHP> 5.0 btw.

!#######编辑解决方案(但没有回答问题)#########!

如果你很好奇,我的解决方法是在静态函数中实例化我的静态函数类.

所以,班级名称是Page I会这样做......

public static function get_info($type){
            $page = new Page();
            switch($type){
                case'title':
                    $page->get_title(); 
                    break;
            }
        }
  public function get_title(){
            return 'Title';
        }
Run Code Online (Sandbox Code Playgroud)

MrW*_*ite 10

这实际上没问题,就我所见,这里没有什么是不可能的.你的静态get_title()方法可以是私有的 - 或者我错过了什么?如果你的静态方法get_info()get_title()它们在同一个类中(无论它是否是静态的)那么你的get_title()方法可以是私有的,你的代码仍可正常工作而不会出错.在类中get_info()调用get_title()- 静态.get_title()在您的示例中不需要公开,除非需要从静态类外部访问它.

Access(public,protected和private)适用于静态类(所有方法都是静态的)以及类实例.

编辑:你不需要求助于实例化类来实现私有访问...

// Enable full error reporting to make sure all is OK
error_reporting(E_ALL | E_STRICT);

class MyStaticClass {

 public static function get_info($type){
  switch($type){
   case 'title':
    return self::get_title(); 
    break;
   }
 }


 private static function get_title() {
  return 'Title';
 }
}

// OK - get_info() calls the private method get_title() inside the static class
echo MyStaticClass::get_info('title');

// ERROR - get_title() is private so cannot be called from outside the class
echo MyStaticClass::get_title();
Run Code Online (Sandbox Code Playgroud)


Nic*_*s78 2

是的,这是不可能的 - 非静态方法需要一个对象来读取数据,而静态方法的要点是它没有附加这样的对象。您可以认为每个非静态方法都传递一个隐式参数,即对象。如果您从静态函数调用,则根本没有值可以将该值传递给该方法。

更新 您可以拥有私有静态函数 - 我不确定您的问题是否可能涉及对私有和静态作为互斥概念的轻微误解