Home >Backend Development >PHP Tutorial >How to Fix the PHP \'Non-Static Method Call Statically\' Error?
When attempting to access a non-static method as a static function, PHP generates the error message Strict standards: Non-static method should not be called statically. This issue often arises when a class method is utilized without first instantiating an object of the class.
1. Specify Class Object:
To solve this issue, you need to create an instance of the class before attempting to call its methods. For example, instead of:
Page::getInstanceByName($page);
Use:
$pageInstance = new Page(); $pageInstance->getInstanceByName($page);
2. Mark Method as Static:
If you intend to call a method without instantiating the class, you can define the method as static within the class. For example:
class Page { public static function getInstanceByName($name) { // method implementation } }
This allows you to call the method directly using the class name:
Page::getInstanceByName($page);
1. Testability:
Note that static methods and singletons can hinder testability. You may want to consider alternative design patterns to improve testing capabilities.
2. Constructor Optimization:
Avoid placing excessive tasks in the constructor. The constructor should only handle setting the object into a valid state. Consider injecting data dependencies rather than fetching them directly from the constructor. Remember that constructors cannot return values and always return void.
The above is the detailed content of How to Fix the PHP \'Non-Static Method Call Statically\' Error?. For more information, please follow other related articles on the PHP Chinese website!