PHP Basics

Using Static Methods In PHP

A static method allows us to use the method without creating the object first.

This means that we can use the scope resolution operator :: to use the method. Static methods can not be accessed by using the normal arrow -> on classes.

class new_class
     //New static method
     public static new_method(){


To access the new_method() we need to use the :: operator.


If we try using it the normal way it will throw an error.

$newClass = new new_class();

You can use the :: operator to access non-static methods will throw a E_STRICT level warning.

As static methods can't be accessed from the a created object we can not use the $this variable to access the method inside the class, instead you need to use self::new_method.

class Foo
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;

class Bar extends Foo
    public function fooStatic() {
        return parent::$my_static;

When To Use Static Methods

When to use a static method is entirely up to you, but I tend to use them when I have no business logic to put in the method and their main functionality will be to output a piece of code or a variable. Static method can be up to 33% faster than normal methods, so if they don't need any business logic these are perfect for outputting data.

class static_method_class
     public static output_header_tag(){
          echo '<head>';

     public static output_end _header_tag(){
          echo '</head>';

     public static output_body_tag(){
          echo '<body>';

     public static output_end_body_tag(){
          echo '</body>';

$static_method_class::output_header_tag() //Output <head>
$static_method_class::output_end_header_tag() //Output </head>
$static_method_class::output_body_tag() //Output <body>
$static_method_class::output_end_body_tag() //Output </body>
Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial