我可能会问这个问题,所以我打算举个例子。我有一个与此类似的课程:
class myclass {
var $template = array();
var $record = array();
function __construct($template,$record) {
$this->template = ( set = to a database response here );
$this->record = ( set = to a database response here );
}
我的问题是,当使用此对象时,模板应始终相同,并且记录是对象的每个实例的更改。有没有办法让$ template的值转移到每个新实例?像
这样的东西$a = new myclass(1,500);
$b = new myClass(2);
其中b具有创建$ a时已生成的$this->template
的值。也许我完全从错误的角度接近这个。任何建议表示赞赏。
答案 0 :(得分:3)
是。 Declaring it static会使其成为一个类属性
class Counter {
public static $total = 0;
public function increment()
{
self::$total++;
}
}
echo Counter::$total; // 0;
$a = new Counter;
$a->increment();
echo $a::$total; // 1;
$b = new Counter;
echo $b::$total; // 1;
注意:我使用$ a和$ b来访问静态属性,以说明该属性同时适用于这两个实例的要点。此外,这样做仅适用于5.3。在此之前,你必须做Counter :: $ total。