tags:

views:

24

answers:

1

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.

+3  A: 

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.

Gordon
You should probably mention how it can be accessed ;)
Lior Cohen
Oookay, but I can't set a static variable to a function which I would need to in order to get the info out of the database.
Stomped
"set a static variable to a function", what does this mean and how on earth is that related to a database?
Lior Cohen
@Gordon - $a::$total wouldn't be a very good approach. Why reference a class property via its instance? This is PHP4 behavior being carried over to PHP5 with its more solid OOP approach. You should probably replace that with a method call or use Counter::$total instead.
Lior Cohen
Thanks for the expanded explanation. I guess for each instance, I can check if the value for class::template has been set, and if not, set it
Stomped
@Stomped: right.
Lior Cohen
@Lior to illustrate the point that the value is the same regardless from where it is called $a or $b. However, I should add that accessing the static property like this works from PHP5.3 onward only
Gordon
I should mention that in my previous comment, I meant PHP4 style behavior and not necessarily syntax. While this "feature" was indeed added in PHP 5.3, I still think class properties should be referenced from... the class (if only for the sake of clarity). +1, anyways.
Lior Cohen