Static Methods and Properties In PHP

We’ve recently dived deep into the basics of Object-Programming language in PHP, in this guide, we would look into static methods and properties.

In the OOP guide, I said class describes the concept of creating an Object, there are not necessarily the objects themselves, but as a code template used to create or generate one or more objects.

Well, this isn’t quite black and white, you can in fact access both methods and properties in the context of a class rather than that of an object when using static methods and properties, a value of a static method is not relative to a certain object instance but to the class itself.

Meaning, the static methods are functions with class scope, you don’t have to instantiate an object to access them, although they cannot access any normal properties in the class because, offcourse, it would belong to an object, however, they can access static properties.

If you change a static property, all instances of that class are able to access the new value.

Normally, to access an element via an object, we would do something like:

print ($artiste_info->getartisteinfo());

This kinda makes sense, since we are accessing via an object, it is different when accessing static element via a class, you do not need a variable that references an object. Instead, you use the class name in conjunction with::, like so:

StaticExample::passValidate;

This syntax was used in conjunction with parents to access an overridden method in the OOP guide, so, it is basically the same when accessing class rather than object data.

Before we go further, what is the purpose of static methods and properties?

You can use a static method if you don’t want the functionality of a method to depend on an object instance, in other words, if something is not gonna change often, use a static method.

Here is an example:

					

<?php

class User {
    protected $name;
    protected $email_address;
    public static $minPassLen = 8;
    
    
}

Can you guess what’s not gonna change often in the above code? It is obviously the $minPassLen, the $name and $email_address will always change depending on how many instances you want to make, but $minPassLen will always be the same no matter what, which is why we are using a public static for the property $minPassLen.

Here is another example:

					

<?php

declare(strict_types=1);

class User {
    protected $name;
    protected $email_address;
    public static $databaseuser = "admin";

    public static function dbuser()
    {
        print self::$databaseuser;
    }

}

User::dbuser();

// Output =>
# admin

Instead of using the $this pseudo-variable, we use the self keyword, self is to classes, and $this is to objects. As you can see from outside the class, we can access the $databaseuser property using the class name:

User::dbuser();

No need to instantiate no objects.

Here is an example that checks minimum password length:

					

<?php

declare(strict_types=1);

class User {
    protected $name;
    protected $email_address;
    public static $minPassLen = 8;

    public static function minPassLen($pass) {
        return strlen($pass) >= self::$minPassLen;
    }

}

$password = 'Iambigg';
print (User::minPassLen($password)) ?  'Password valid' :  'Password NOT valid';

// Output => 
Password NOT valid

We are using the strength function to test the length of the $pass that is passed in should be greater than or equals to the static property: self::$minPassLen, which is 8. So, if it is greater or equals to 8, it would return true otherwise false.

This:

return strlen($pass) >= self::$minPassLen;

can also be written as:

					

if(strlen($pass) >= self::$minPassLen){
            return true;
        } else {
            return false;
        }

or using a ternary operator:

					

return strlen($pass) >= self::$minPassLen ? true : false;

As you can see, the first one is shorter, and readable…moving on…

Outside of the class, we then pass a value:

					

$password = 'Iambigg';
print (User::minPassLen($password)) ?  'Password valid' :  'Password Too Short';

If the password we passed in is lesser than 8, it would return “Password Too Short”, if otherwise, it would return password valid. All this is programmatically possible by just passing an argument to the static method.

As you can see, we don’t have to instantiate any new objects, it just works.

Note, this:

print (User::minPassLen($password)) ?  'Password valid' :  'Password Too Short';

can be written as:

$password = 'Iambigg';
if(User::minPassLen($password)){
  echo 'Password valid';
} else {
  echo 'Password Too Short';
}

Note that, you will often see static syntax used to refer to a method or property. This does not mean that the property in question is necessarily static, just that it belongs to a certain class.

Before rounding up this guide, let’s take a look on…

Constant Properties

Just like a static property, a constant property is relative to a class, and not an object. Meaning, constant properties are accessed through the class and not an instance.

Here is an example:

					

class musicShop {
    const STATUS_ON = 1;
    const STATUS_OFF = 0;
    const OUT_OF_STOCK = 0;
    // ...

As you can see, it is no different from a standard constant, it doesn’t have a dollar sign nor leading symbol. So, to refer to the constant property, you do:

					

print musicShop::STATUS_OFF;

It is as simple as it get. Note: Trying to set a value on a constant once it has been declared will cause a parse error. It is a constant and can’t get redefined.

So, I guess that would conclude the guide on static methods, properties, and constant properties.

Posted in PHP

Comment policy: Respectful and beneficial comments are welcome with full open hands. However, all comments are manually moderated and those that doesn't relate with what the passage is saying or offensive comments would be deleted. Thanks for understanding!

Leave a Reply

Your email address will not be published. Required fields are marked *