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
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top