Forum Moderators: coopster

Message Too Old, No Replies

PHP equivalent to C++ class static

PHP static and C++ static

         

hyper_ion

3:21 pm on Nov 30, 2011 (gmt 0)

10+ Year Member



I am new to PHP in general and PHP oop specifically and it has been a while since I used C++, but I seem to recall that you could created a kind of "shared" variable across ALL instances of a class using the Static keyword in your property declaration.

Is there a way to accomplish this with PHP objects?

I need to have all instances of a class have access to a shared array.

Thank you for any assistance you can give me.

penders

4:28 pm on Nov 30, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yes, in pretty much the same way... using the
static
keyword. The static property values are shared among all instances of the class. In this sense, they are 'class variables'.

class ClassA { 
public static $myStaticVar = 'Hello World';
private static $_myPrivateStaticVar = 'Foo Bar';
public static function getPrivateVar() {
// Must be accessed statically (not via $this)
return self::$_myPrivateStaticVar;
}
}


// Public static property 
echo ClassA::$myStaticVar; // 'Hello World'
// Private static property can be accessed via accessor method only
echo ClassA::getPrivateVar(); // 'Foo Bar'
// ...or via class instance
$myInstanceA = new ClassA();
echo $myInstanceA->getPrivateVar(); // 'Foo Bar'


However, static variables should be used with caution. They are frowned upon by many as the do break certain OOP principles, namely encapsulation, and can make debugging harder.

hyper_ion

2:50 am on Dec 1, 2011 (gmt 0)

10+ Year Member



So to stick with your example, if I wanted to have each instantiated object have a unique numerical identity, could I use the following:
class ClassA {
public static $myCounter;

then in the constructor method, increment it using self::$myCounter++;
assign that to a private property and each instantiated object has an identifier.
$this->myNumber = self::$myCounter;

I get that this might not be good programming practice, but would it work?

penders

9:00 am on Dec 1, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yes that would work. $myCounter could be private as well if you wanted. And $myCounter should perhaps be initialised before attempting to increment it...
public static $myCounter = 0;

hyper_ion

1:50 pm on Dec 1, 2011 (gmt 0)

10+ Year Member



Okay, thanks.