Static Keyword | Object Oriented Programming in PHP

We discussed public and private Access Modifiers earlier. Sometimes, we require access to a Class’s members without creating an object. In this situation, we use Static Keyword in PHP. Defining a class property static makes it accessible without instantiating an object of the class. In this article, we will discuss the use of Static Keyword in PHP.

Please go through the introduction of Object Oriented Programming in PHP first.

Difference Between Non-Static and Static Members

The following table explains the difference between Static and Non-Static Members.

CriteriaNon-Static MemberStatic Member
Class/Object LevelThey are Object Level Members.They are Class Level Members.
CopiesEvery Object has a different copy.The whole class has a single copy.
CallingAn object instance is required to call the member.Members are called directly using the Class Name. From within the class, self keyword is used.
Memory AllocationEvery Object has a different Memory Allocation.All the Objects have a single Memory Allocation for Static Members.

Basic Usage of Static Keyword

For instance, let’s go through the basic usage of Static Keyword.

<?php
	
	class Logger {

		public static $logPath = '/tmp/log/';

	}
	echo Logger::$logPath;
        ///tmp/log/
?>

We have a Logger class in the above example. Also, there is a static member variable logPath. In order to access the static variable, we don’t need to initialize an object of the class. We can do it directly using the Class Name as shown.

Static Methods

Similarly, we can define Static Methods also. Static Methods are also called using the class reference. Static Methods should be used in a case when you don’t need an object reference inside the method.

Warning: In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.

<?php

	class Logger {

		private static $logPath = '/tmp/log/';

		public static function log() {
			echo 'Log Method Called';
		}

	}
	Logger::log()
	//Log Method Called
?>

We have added a static log method in the Logger Class. We can call that method with the class name without instantiating an object.

When to Define Static Methods?

You should create a static method when it makes sense to call it without needing an object. If a logic can be shared by different methods then it can be copied in a static method. PHP static methods are often used in utility classes of  PHP frameworks. A utility class is a class that contains only static methods.

Self Keyword: Accessing Static Members in Methods

We can also have Private Static Members. Also, we might need to access a static member within the class. You can use the ‘self’ keyword to access static members within the class.

<?php

	class Logger {

		private static $logPath = '/tmp/log/';

		public static function log() {
			echo self::$logPath;
		}

	}
	Logger::log()
	///tmp/log/
?>

The static log method is called with the class name. Inside the log method, the static member logPath can be accessed by using the self keyword.

self vs $this Keyword

This brings us to a very important question. What is the difference between $this and self? It looks a bit confusing to many developers. Hence, they decide not to use static members at all!

$thisself
Reference to the ObjectReference to the Class
It is followed by -> operatorIt is followed by :: operator
Cannot be used in static methods.Can be used in static and non-static methods.

Using $this in Static Methods

We don’t need to create an object to call a Static Method. As a result, we don’t have any object reference inside the called method. Hence, $this is not available inside a Static Method. For example, go through the code snippet:

<?php
	class Logger {

		private static $logPath = '/tmp/log/';
		private $logLevel = 1;

		public static function log() {
			echo $this->logLevel;
			//Fatal error: Uncaught Error: Using $this when not in object context
		}

	}
	Logger::log()
?>

Accessing a non-static property logLevel inside a static method results in a Fatal Error. However, you may access static members in a non-static method by using the self keyword.

Memory Allocation

Static Members have the same memory allocated for the whole class. Therefore, all the different objects refer to the same memory when accessing a static member. For instance, consider the following code snippet:

<?php
	class Counter {

		private static $count = 10;
		private $nonStaticVariable = 5;

		public function doCount() {
			self::$count++;
		}

		public function incrementNonStaticVariable() {
			$this->nonStaticVariable++;
		}

		public function getNonStaticVariable() {
			return $this->nonStaticVariable;
		}

		public function getCount() {
			return self::$count;
		}
	}

	$counter1 = new Counter();
	$counter2 = new Counter();

	$counter1->incrementNonStaticVariable();
	print_r($counter2->getNonStaticVariable());
	//Prints 5 as the variable is non static and all obejcts have different memory allocations

	$counter1->doCount();
	print_r($counter2->getCount());
	// Prints 11 as the $count is static and only one memory is allocated for the whole class
?>
  • We define a Counter class with one static and one non-static member variable.
  • Instantiate 2 objects of the Counter Class ($counter1 and $counter2).
  • Increment the non static variable value for $counter1. We observe that the non static value of $counter2 is not incremented and is the same.
  • Now, increment the static member value ($count) for $counter1. It can be observed, the static member for $counter2 is also incremented as they both share the same memory.

Conclusion

In conclusion, we discussed the use of Static Keyword in this article. It is very important to understand it’s working for future articles. Also, you may read more about static variable on PHP Official Documentation.

Spread the Knowledge

Leave a Reply

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