Static Methods and Properties

Last updated

What is Static Methods and Properties?

Static methods and properties in PHP belong to the class rather than an instance of the class. This means they can be accessed without creating an object of the class. A static method is declared with the static keyword and can be invoked directly using the class name followed by the scope resolution operator. Similarly, a static property is also defined with the static keyword, but cannot be accessed directly, even from within the class methods - they must be accessed through static methods. Here's a simple example:

class MyClass {
    static $myStaticProperty = "Hello, world";

    static function myStaticMethod() { 
        return self::$myStaticProperty; 
    }
}

echo MyClass::myStaticMethod(); 

In this example, we're directly accessing myStaticMethod from MyClass without an instantiation.

Free resources to learn Static Methods and Properties

More in stage 11: OOP Fundamentals

Static Methods and Properties: common questions

Can I learn Static Methods and Properties in Hindi?

This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Static Methods and Properties in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.

Is this Static Methods and Properties tutorial for beginners?

It is lesson 65 of 120 in the free PHP roadmap, in stage 11, OOP Fundamentals. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.

Still confused? Ask me