In PHP, static methods and non-static methods are two different types of methods in object-oriented programming. Static methods belong to the class level and can be called without creating an instance. They are typically used for general operations related to the class and are marked with the static keyword. Non-static methods are instance-level and must be called through an object instance, usually to manipulate instance properties and other instance methods.
Static methods can directly access static properties and static methods of the class without an instance. Non-static methods can access static properties and methods as well as instance properties and methods via $this.
Since static methods cannot use $this to access non-static properties and methods, to call a non-static method, you can use one of the following approaches:
You can pass an instance object as a parameter to the static method, then call the non-static method via that object:
class MyClass {
public $name = "John";
public function hello() {
echo "Hello, " . $this->name;
}
public static function accessNonStaticMethod($obj) {
$obj->hello();
}
}
$obj = new MyClass();
MyClass::accessNonStaticMethod($obj);
This approach requires passing the object every time and can be somewhat cumbersome.
Another way is to instantiate the class inside the static method and then call the non-static method:
class MyClass {
public $name = "John";
public function hello() {
echo "Hello, " . $this->name;
}
public static function accessNonStaticMethod() {
$obj = new self();
$obj->hello();
}
}
MyClass::accessNonStaticMethod();
This method does not require external parameters and is cleaner but suitable only for certain scenarios.
Here is a complete example demonstrating both ways for a static method to call a non-static method:
class MyClass {
public $name = "John";
public function hello() {
echo "Hello, " . $this->name;
}
public static function accessNonStaticMethod() {
$obj = new self();
$obj->hello();
// Or call by passing instance
// $obj = new self();
// self::accessNonStaticMethod($obj);
}
}
MyClass::accessNonStaticMethod();
Note that $this cannot be used inside static methods to access non-static members. Always ensure an appropriate object instance exists when calling non-static methods.
Static and non-static methods are essential components of PHP OOP. Static methods can access static members directly, while non-static methods require an object instance. To have static methods call non-static methods, pass an instance or instantiate one inside the static method; direct use of $this is not possible. Choosing the right approach and maintaining clear, maintainable code is crucial in practice.