【发布时间】:2011-04-02 07:21:55
【问题描述】:
什么时候应该在 PHP 中使用静态函数/类/字段?它有哪些实际用途?
【问题讨论】:
-
如果您正在尝试编写面向对象的代码:从不。
什么时候应该在 PHP 中使用静态函数/类/字段?它有哪些实际用途?
【问题讨论】:
你不应该,它很少有用。 静态的常见用法是工厂方法和 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();
}
}
【讨论】:
在 Java/PHP 等语言中使用相同的静态方法。
一个简单的例子是,您希望在类的所有实例中使用一个变量,并且任何实例都可以更改其值,并且您希望它也反映在其他实例中。
class Foo{
static $count=0;
public function incrementCount(){
self::$count++;
}
public function getCount(){
return self:$count;
}
}
没有静态,您无法通过一个对象设置计数值并在其他对象中访问它。
【讨论】:
当我需要在类中使用的简单函数时,我偶尔会使用静态方法,这些函数我也在类外使用,例如:
在 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);
我确实维护了一个常用用户定义函数库,但我发现在与其密切相关的类中包含一些函数很方便。
【讨论】: