【问题标题】:Initiating a class globally全局启动类
【发布时间】:2013-12-19 06:18:14
【问题描述】:

具体来说,我有两个类 Request 和 Utils,

class Request
{
public function __construct()
{
//constructor method
}
public function request()
{
  $utils=new Utils;
  $consolidated_errors=$utils->array_remove_empty($all_params_error);
}   
public function process()
{
  $utils=new Utils;
  $consolidated_errors=$utils->another_method($all_params_error);
 }                                                                   
}

还有类 Utils,

class Utils
{
public function __construct()
{
 //constructor method
}
public function array_remove_empty()
{
  //returns a variable.
  }        
public function another_method()
{
  //returns a variable.
 }     

}

你可以看到我在请求类中初始化了两次类,我的问题是,有什么方法可以全局初始化类并在整个类中使用?

【问题讨论】:

  • 你贴的代码是PHP代码,为​​什么要在java下打标签?

标签: php class oop


【解决方案1】:

您正在寻找单例模式

以下为您的班级演示非常基本的单例示例

public class Utils {
  private static Utils uniqInstance;

  private Utils() {
  }

  public static synchronized Utils getInstance() {
    if (uniqInstance == null) {
      uniqInstance = new Utils();
    }
    return uniqInstance;
  }
  // other useful methods here
} 

使用静态工厂模式获取实例

【讨论】:

    【解决方案2】:

    上面的代码在我看来并不像 Java,但无论如何,

    您可以在班级级别创建班级private Utils myUtuils = new Utils ();

    或 将类作为静态类,然后直接在您的方法中使用它

    public function process()
    {
      consolidated_errors= Utils.another_method($all_params_error);
     }                                                                   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2020-11-15
      • 2013-10-27
      • 2013-06-17
      相关资源
      最近更新 更多