OOP: Instance Vs. Static
By: Ryan Kienstra on: January 18, 2015 in: OOP For WordPress
By understanding instance vs. static properties, you can write flexible code.
And build complex object-oriented programs.
If you aren’t familiar with classes and instances, you might read OOP Fundamentals For WordPress.
Properties: Instance Vs. Static
Instances can store variables called instance properties.
They aren’t connected to properties of other instances.
But instances can also access static properties.
They’re the same in every instance of the same class.
Why Static Properties?
All instances can access common data.
They can do something based on what other instances have done.
For example, in my Adapter Post Preview WordPress plugin, the class APP_Carousel
creates a carousel.
There’s a separate instance of the class for each carousel.
Every carousel (instance) needs a unique id: 1, 2, 3…
So I set the $instance_id
as a static
property.
Every instance has access to it.
And each new instance will know the latest id that was used.
How To Use Static Properties
class APP_Carousel { protected static $instance_id = 1; protected $carousel_id; protected $carousel_inner_items; protected $number_of_inner_items; protected $carousel_indicators; protected $slide_to_index; protected $post_markup; public function __construct() { $this->carousel_id = 'appw-carousel-' . self::$instance_id; self::$instance_id++;
To set a property as static, place static
before it in the top of the class.
protected static $instance_id = 1;
To access static properties, use self::
.
$this->carousel_id = 'appw-carousel-' . self::$instance_id;
In the __construct()
function, I incremented (increased) $instance_id
by 1
.
self::$instance_id++;
The next time the constructor is called to create an instance, $instance_id
will be 1 higher.
Can Be Changed
Static properties aren’t static in the normal sense of the word.
They can be changed by instances or the class.
If you don’t want a property to be changed, use final
before it.
final $foo_property = 'example_string';
I’ve mistaken static
and final
before.
Further Study: Static Methods
static
means connected to a class, not an instance.
So methods (functions) can be static, as well.
Read more about this in the PHP Documentation.
More Flexibility
You’ve read about instance vs. static properties.
But the most flexible aspect of classes is inheritance.
In the next guide, see how classes can use parts of other classes.
Then, you can build on other complex systems.
For example, WordPress widgets use class inheritance.
Do you have any questions about this?
Leave a comment below.