Static Methods and Properties In PHP

In my last tutorial, What Object-Oriented Programming Is NOT, I mentioned that over-using or mis-using the static keyword is one way developers get confused with object-oriented programming. That, often, they simply take their procedural code, dump into a class, make everything static and away we go.

That said, there CAN be legitimate uses for fully static classes.

I like the answer Pascal MARTIN gave on StackOverflow:

The distinction I make is this:

  • Use an instantiated class for actual objects in your applications (post, category, user, etc)
  • Use a static class for “libraries of code” that have useful functions

As Pascal said, that’s probably over-simplified, but it helps me keep my head straight. Of course, the question becomes… how do we write a static class.

The first thing to keep in mind is “once you go static, you can’t go back”… in a way. More specifically, you can’t use object properties or methods in static methods. So, this won’t work:

<?php
class Library {
    public $var = 'Hey';
    
    public static function do_stuff() {
        echo $this->var;
    }
}

Library::do_stuff(); // Triggers: Fatal error: Using $this when not in object context

That’s because $this references and instantiated object. But, we bypass that when using static methods. So, $this essentially doesn’t “exist”. But, you might think you could do this:

<?php
class Library {
    public $var = 'Hey';
    
    public static function do_stuff() {
        echo Library::$var;
    }
}

Library::do_stuff(); // Triggers: Fatal error: Access to undeclared static property: Library::$var

So, once you declare a method static… basically everything it touches has to be static, too. Thus, this is what works:

<?php
class Library {
    public static $var = 'Hey';
    
    public static function do_stuff() {
        echo Library::$var;
    }
}

Library::do_stuff(); // Outputs "Hey"

One way you might use this, then, is something like this:

<?php
class Library {
    public static $date_format = 'F jS, Y';
    
    public static function format_date($unix_timestamp) {
        return date(self::$date_format, $unix_timestamp);
    }
}

echo Library::format_date(time()); // Outputs formatted date

The format_date() method is one that could be used in various places throughout your application and wouldn’t need constantly re-instantiated to use. And, of course, this Library class could contain various, similar methods that have data-agnostic uses. A kind of “catch-all” for miscellaneous functions.

And, of course, as you’ve seen the way to make a property or method static is to simply add the “static” keyword to the declaration, like so:

<?php
class Library {
    public static $var = 'Hey';
    
    public static function do_stuff() {
        // do stuff
    }
}

So, there you go. Now, if you want to keep going and learn how to build professional PHP applications using object-oriented programming, then check out my full object-oriented programming course here (also available on Udemy here).

You might also like

Get off your knees

Stop acting like your client’s servant — like you’re there to kowtow to their every whim and wish and you’re lucky they’ve graced you with

Read More »

Chicks dig this s***

Saw this scrub on Twitter post this namby-pamby bullshizen: === I will NEVER be impressed by your money, car, looks, social status or job title.

Read More »
Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on reddit
Reddit
Share on pinterest
Pinterest
John Morris

JOHN MORRIS

I’m a 15-year veteran of freelance web development. I’ve worked with bestselling authors and average Joe’s next door. These days, I focus on helping other freelancers build their freelance business and their lifestyles.

The simple secrets to high-paying freelance clients

What makes clients willing to pay $5,000, $10,000 even $20,000 and up for your services? Download and install my mobile app and I’ll show you. It’s free. Just click the button below:

Clients Like:

Inc. Magazine Logo
Lewis Howes Logo
Ray Edwards Logo

WHAT OTHERS ARE SAYING

Bob Patterson

Not only is John a very talented programmer and developer, he is also an excellent communicator. He has a talent for taking complex subjects and communicating them in terms that anyone can understand. This is a rare combination. This ability has enabled me to take my skills and knowledge to the next level. Thank you John for for all that you do.

Sukh Plaha

John is a fantastic and patient tutor, who is not just able to share knowledge and communicate it very effectively – but able to support one in applying it. However, I believe that John has a very rare ability to go further than just imparting knowledge and showing one how to apply it. He is able to innately provoke one’s curiosity when explaining and demonstrating concepts, to the extent that one can explore and unravel their own learning journey. Thanks very much John!

Aaron Gott

Aaron Gott

John has a particular knack for the development and training of others.

Michael Skye

Michael Skye

John is a man of integrity, who gives generously of himself to projects and people he cares about.

Bradley Smith

John and I have worked together on numerous projects. John is very quick and efficient and was a pleasure to work with.

Lori Grant

John did an outstanding job on my project. I highly recommend him and look forward to working with him on future projects.

Jim DeJonge

Jim DeJonge

John has a relaxed and engaging manner. His advice is solid and the explanations are well thought out.

Ray Edwards

I recommend John every chance I get. If every person I worked with were as committed to excellence, punctuality, value, and unquestionable integrity… the world would be a better place. Highest recommendation.

Chris Aitken

He significantly improved my site through his expert knowledge of PHP, CSS and Javascript. Would definitely recommend John to others.

Andrew Malone

Andrew Malone

John Morris is exceptional in his ability to give focused insight into Freelancing and starting one’s business. His direct methods inspire confidence in his honesty.

Jason Rumley

Jason Rumley

John has a habit of over-delivering on the expectations he sets up. That’s why he’s the best.

Daniel Mohlendick

On the Freelancing on Upwork course: “This is by far the best course i have watched on Skillshare!! Thank you so much.”

Steve Dimmick

Steve Dimmick

John has provided expert knowledge and advice on multiple occasions that have helped me better serve my clients. John is a Rockstar!