Let’s learn how to create static methods and properties. Anything that’s static is basically something that can be accessed without needing an instantiation of the class. You also have the advantage of having a value that is consistent through each instance of the class. Let’s take a look at this.
Creating Static Properties
Inside our Pet Class, add this bit of code.
protected static $petsCreated;
The static keyword tells PHP that this is a static property. We’re creating a property that will hold the value for the amount of pets created. Since this property is static, it’ll always be the same value throughout all instances of the Pet class. You don’t have to define the scope of the property. By default, static properties are set to public. We’ll see how this works in a bit.
In our construct method, add this line of code.
As you can see, we’re not using the object operator, but the scope resolution operator to access this property. You must use the scope resolution operator or else you’ll get an error. The self keyword refers to the class itself.
Lastly, let’s create a static method that will return the amount of pets created when we need it.
public static function getPetsCreatedTotal()
Once again, we’re using the static keyword to tell PHP this is a static method. We use the self keyword again to grab the value. You’ll notice that we’re not omitting the $ from the property name like we would a constant. To grab static properties, you must use the $. We then return this value.
In our index.php file, update your code to this.
$jack = new Pet( 'Jack ' );
$sam = new Pet( 'Sam' );
Open this file in your web browser and you should see 2. As you can see, when we create a new instance of the Pet class, the $petsCreated property is updated by 1. By updating the value in one instance of the class, any other instance using the same class is then updated to correspond with the latest value.
I also mentioned you can access this class without creating an instance of this class. We can update our last line of code to this.
As you can see, static methods and properties can be very useful and powerful when creating classes. You gain the power of having a constant method or property throughout all instances while also being able to change the value. If you would like more information about static methods and properties, then go here.