is there a way to set a class variable to apply to all instances of that class in php?

StackOverflow https://stackoverflow.com/questions/2379832

  •  24-09-2019
  •  | 
  •  

문제

I'm probably asking the question badly, so I'm going to give an example. I have a class that is something similar to this:

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

My issue is when using this object, the template should always be the same, and the record is what changes for each instance of the object. Is there a way to have the value for $template carry over to each new instance? Something like

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

Where b has the value for $this->template that was already generated when creating $a. Maybe I'm approaching this from the wrong angle entirely. Any suggestions appreciated.

도움이 되었습니까?

해결책

Yes. Declaring it static will make it a class property

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top