facebook youtube pinterest twitter reddit whatsapp instagram

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 Too Short';

// Output => 
Password Too Short

We are using the strlength function to test the length of the $pass that is passed in, and 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.

Related Post(s)

  • Laravel - Edit and Delete Data (+ User Authentication)

    In this guide, you'll learn how to edit and delete post data in Laravel, before proceeding you should read the previous guides as this guide would be the continuation, here are the previous guides:

  • Guide To Laravel - Model and Database Migrations

    I don't know if you have read my guide on Creating a Tiny PHP MVC Framework From Scratch where we create a tiny MVC framework in the hope of understanding the concepts of how major frameworks imple

  • Building Dependency Injection and The Container from Scratch in PHP

    In this guide, you'll learn about dependency injection and a way to build a simple DIC (Dependency Injection Container) in PHP using PSR-11 from scratch. First, What is an Ordinary Dependency? This

  • Creating a Tiny PHP MVC Framework From Scratch

    In this guide, we would go over creating a tiny PHP MVC Framework, this would sharpen your knowledge on how major frameworks (e.g Codeigniter or Laravel) works in general. I believe if you can unders

  • PHP Pluggable and Modular System – Part 2 (Implementation) [Event Dispatcher]

    In the first series of this guide, we discussed the theoretical aspect of building a pluggable system in PHP, I wrote a bit of code in that guide plus a couple of stuff you should avoid, you can lear

  • Best Way To Implement a Non-Breaking Friendly URL In PHP or Laravel or Any Language

    I was working on the link structure of my new Laravel app, and out of the blue I said: "What would happen if a user changes the slug of a post?" First Attempt - 301 Redirection The first solution I t