【问题标题】:When to use static methods/fields in PHP?何时在 PHP 中使用静态方法/字段?
【发布时间】:2011-04-02 07:21:55
【问题描述】:

什么时候应该在 PHP 中使用静态函数/类/字段?它有哪些实际用途?

【问题讨论】:

  • 如果您正在尝试编写面向对象的代码:从不

标签: php static


【解决方案1】:

你不应该,它很少有用。 静态的常见用法是工厂方法和 singleton::instance()

工厂:

class Point{
  private $x;
  private $y;

  public function __construct($x, $y){
    ...
  }

  static function fromArray($arr){
    return new Point($arr["x"], $arr["y"]);
  } 
}

单例:

class DB{
  private $inst;

  private function __construct(){
    ...
  }

  static function instance(){
    if ($this->inst)
      return $this->inst;

    return $this->inst = new DB();
  }
}

【讨论】:

  • 我同意这几乎没有必要和有害。我会添加一个有用的案例:创建更高级别的语言。例如用户::with100Points()。更多内容可以在《以测试为指导的面向对象的软件发展》一书中找到。
  • @koen 再解释一下,User::with100points() 将如何工作?
  • @Click Upvote 如果你的意思是它在代码中的样子: class User { public function setPoints($points) { //set points } public static function with100points() { return new self(100); } }。 User::with100points() 比 $user = new User(); 更具可读性$user->setPoints(100);你可以为这个 DSLUser 创建一个特殊的类 extends User { public static method with100points() {} }。在您的代码中正确使用它的机会并不多,但在 UnitTests 中您可以更多地使用它,并且您的测试通常会变得非常清晰。
【解决方案2】:

在 Java/PHP 等语言中使用相同的静态方法。

一个简单的例子是,您希望在类的所有实例中使用一个变量,并且任何实例都可以更改其值,并且您希望它也反映在其他实例中。

   class Foo{
    static $count=0;
    public function incrementCount(){
    self::$count++;
    }

   public function getCount(){
    return self:$count;
   }
  }

没有静态,您无法通过一个对象设置计数值并在其他对象中访问它。

【讨论】:

    【解决方案3】:

    当我需要在类中使用的简单函数时,我偶尔会使用静态方法,这些函数我也在类外使用,例如:

    在 UserProfile 类中,我有一个方法返回一个数组,该数组用于在从 html 页面填充数组后将数据传递回类。

        Class UserProfile{
    
            Public Static get_empty_array(){
    
                return array('firstname'=>'',lastname=>''); //usually much more complex multi-dim arrays
    
            }
    
        }
    

    这样,空数组可以在类/对象内部和外部用作起始模板。 我还对通常是独立函数的函数使用静态方法,但我想将它们保留在类中,以便它们在一起,但也使它们作为静态方法在外部可用,例如:

        public static convert_data($string){
    
            //do some data conversion or manipulating here then
    
            return $ret_value;
    
    
        }
    
        $converted_data = class::convert_data($string);
    

    我确实维护了一个常用用户定义函数库,但我发现在与其密切相关的类中包含一些函数很方便。

    【讨论】:

    • 有点像命名你的全局函数。
    • 另一种说法:如果该方法不影响对象的状态,则它是静态方法的良好候选者。
    猜你喜欢
    • 2013-07-11
    • 1970-01-01
    • 2014-05-24
    • 2017-08-19
    • 1970-01-01
    • 2014-06-04
    • 2010-12-10
    • 2020-03-30
    • 2011-02-09
    相关资源
    最近更新 更多