php o sınıfın tüm örnekleri için geçerli bir sınıf değişkeni ayarlamak için bir yolu var mı?

1 Cevap php

Herhalde kötü bir soru soruyorum, o yüzden bir örnek vereceğim. Ben buna benzer bir şey olduğunu bir sınıf var:

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 );
}

Bu nesneyi kullanırken benim konudur, şablon hep aynı olmalı ve kayıt nesnesinin her örneği için değişen budur. $ Şablona her yeni örneği üzerinde taşıyacak için değere sahip bir yolu var mı? Gibi bir şey

$a = new myclass(1,500);
$b = new myClass(2);

B $ a oluştururken $this->template zaten oluşturulduğu için değeri vardır nerede. Belki de tamamen yanlış bir açıdan bu yaklaşıyorum. Herhangi bir öneriniz takdir.

1 Cevap

Evet. Declaring it static, bir sınıf özelliği yapacak

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;

Note: I used $a and $b to access the static property to illustrate the point that the property applies to both instances simultaenously. Also, doing so will work from 5.3 on only. Before this, you'd have to do Counter::$total.