在php中设置变量类的静态成员


Setting a static member of a variable class in php

我试图添加一个静态成员到我的每个类,其中包含默认的数据库连接,他们应该在实例化时使用。我是这样做的:

<?php //other classes extend Generic
class Generic {
    public static $defaultDatabase;
    public $db;
    function __construct (&$pDatabase = null){
        if ($pDatabase!==null)
            $this->db = &$pDatabase;
        else
            $this->db = &$defaultDatabase;
    }   
}
?>

<?php
include_once("/classes/class.Database.php");
$db = new Database ("localhost", "username", "password", "TestDatabase");
$classes = array("Generic", "Member");
foreach ($classes as $class){
    include_once("/classes/class.$class.php");
    $class::defaultDatabase = &$db;//throws error here, unexpected "="
}
?>

我做错了什么?是否有更好的方法来做到这一点,或者我必须为每个类单独设置defaultDatabase ?我使用的是php 5.3,我知道它应该支持这样的东西。

在此代码中

 $class::defaultDatabase = &$db

你应该在defaultDatabase之前添加$,因为静态属性是通过

访问的

ClassName::$staticProperty

不像其他可以通过

访问的

$class->property;

使用self::$propertyName访问静态属性:

function __construct (&$pDatabase = null){
    if ($pDatabase!==null)
        $this->db = &$pDatabase;
    else
        $this->db = self::$defaultDatabase;
} 

还要注意,如果$var是一个对象,那么使用引用操作符&$var是没有意义的。这是因为PHP中的所有对象实际上都是引用。