Per-Class Constants And Static Methods: PHP OOP

Advertisement:

This video tutorial illustrates the concepts of Per-Class Constants and Static Methods in Object Oriented PHP. Per-Class Constants was introduced in PHP5.

Per-Class Constants
Unlike variables, constants doesn’t change/alter its value during the program execution.
They’re treated as fixed values. Something which doesn’t change in the course of execution.

Since its value remains constant for all the objects, there is no need of an object to be created in-order to access it. We can directly access it using the class name and :: operator and the constant name.

Per-Class Constant
Math.php

1
2
3
4
5
6
7
< ?php
	class Math {
		const pi = 3.14159;
	}
 
       echo Math::pi;
?>

This would output, 3.14159

Static Method
There’re situations where we need to take something which is global to the class.
And there is no use of invoking the method for all objects of that class. In such a situation make use of static methods. This way, you need not instantiate the class to invoke the method.

Syntax to invoke static method: class name, :: operator, method name.

Static Method Invocation
Math.php

1
2
3
4
5
6
7
8
9
< ?php
	class Math {
		static function square($no)
		{
			echo "<br />".$no * $no;
		}
                echo Math::square(10);
	}
?>

This would output, 100

Per-Class Constants And Static Methods: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=0tpX377CEgw [Watch the Video In Full Screen.]



For example,
Declare database connection method as static, so that you can directly use the class name instead of creating an instance of the class.
This way, you can connect to the database, but you don’t have access to other non-static methods of the same class!

Advertisements

1 thought on “Per-Class Constants And Static Methods: PHP OOP”

Leave a Reply

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