Static Methods in PHP

By: Andi, Stig and Derick Viewed: 153172 times    

Similar to static properties, PHP supports declaring methods as static. What this means is that your static methods are part of the class and are not bound to any specific object instance and its properties. Therefore, $this isn’t accessible in these methods, but the class itself is by using self to access it. Because static methods aren’t bound to any specific object, you can call them without creating an object instance by using the class_name::method() syntax. You may also call them from an object instance using $this->method(), but $this won’t be defined in the called method. For clarity, you should use self::method() instead of $this->method().

Here’s an example:

class PrettyPrinter {

static function printHelloWorld()

{

print "Hello, World";

self::printNewline();

}

static function printNewline()

{

print "\n";

}

}

PrettyPrinter::printHelloWorld();

The example prints the string "Hello, World" followed by a newline. Although it is a useless example, you can see that printHelloWorld() can be called on the class without creating an object instance using the class name, and the static method itself can call another static method of the class print-Newline() using the self:: notation. You may call a parent’s static method by using the parent:: notationn.

Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial