如何在PHP类中为静态方法创建构造函数


How to create a contructor for a static method in PHP class

我已经知道如何在类中创建__construct()方法,该方法在您指定的函数执行之前首先执行,当您创建该类的实例时。我的类是静态的,有很多方法——都是静态的。

我想要实现的是创建一个方法,每当调用静态方法时都会执行该方法。这样做的目的是,我想通过将另一个类的实例硬注入静态属性并使用静态属性访问其所有方法来创建一个单例类。

<?php 
class ArrayObject {
  private $input_array;
  private $output_array;
  //this method removes elements with null values
  public function clean(array $array)
  {
    #...code to remove empty value elements
    //set the value of the output to the output array
    $this->output_array  = $result;
  }
  //this method strips whitespace from array element
  public function trim(array $array)
  {
    #...code to remove whitespace
    //set the value of the output to the output array
    $this->output_array  = $result;
  }
  //this method returns the value of the $output_array
  public function getOutput()
  {
    return $this->output_array;
  }
}

上面是要作为依赖项注入到静态类中的对象类。下面是用于实现此ArrayObject 的静态类

<?php 
class ArrayClass {
  private static $arrayObject;
  //this method sets the value of the $arrayObject
  private static function setArrayObject()
  {
    self::$arrayObject = new ArrayObject();
  }
  //this method removes elements with null values
  public static function clean(array $array = null)
  {
    #...call method to remove empty value elements
    self::$arrayObject->clean($array);
    return new static;
  }
  //this method strips whitespace from array elements
  public static function trim(array $array = null)
  {
    #...call method to remove whitespace
    self::$arrayObject->trim($array);
    return new static;
  }
  //this method returns the value of the $output_array
  public static function get()
  {
    return self::$arayObject->getOutput();
  }
}

我这样做的原因是为了能够以这种方式ArrayClass::clean($array)->trim()->get();链接方法。

你可能会说,但为什么不在静态类中完成所有这些,而不是创建一个单独的对象来完成这项工作?我必须创建两个类的原因是,我希望一个类处理数组操作,另一个类在链式环境中获取数组参数,这样我就可以清楚地分离逻辑。

请确保每个方法都需要一个有效的数组。我想对静态类做的是检查链式调用中传递的null值。如果方法调用为空,则静态类将从上一个调用中获取输出数组,并将其作为input_array发送到第二个链接调用,这样,当您想要链接操作时,只将参数传递给第一个方法调用。

现在,希望您已经了解了所有这些,我的问题是:无论何时以任何顺序调用数组操作的任何方法,我如何设置public static function setArrayObject()始终首先执行?-而不必首先在每个静态方法内部调用此方法?如果没有用户,整个类将使用这个类,在访问这个功能之前必须先手动创建一个实例?

从用户的角度来看,我希望这个类的使用是完全静态的。

您是否考虑过使用Factory设计模式?通过这种方式,您可以调用创建对象实例的静态方法,并且可以避免使用像这样的奇怪结构:ArrayClass::clean($array)->trim()->get();

示例:

<?php
class Array {
    // you can implement all your methods here
    public function getOutput() {
    }
    // ...
}
class ArrayFactory {
    public static function create($params) {
        // you can call all necessary cleaning methods here
        // before creating new object
        return new Array($params);
    }
}
// usage:
/** @var Array **/
$array = ArrayFactory::create($params);

希望这能有所帮助。