Home >Backend Development >PHP Tutorial >How to Resolve the PHP Error: \'Non-Static Method Called Statically\'?
PHP Error: Non-Static Method Called Statically
The error message "Strict standards: Non-static method Page::getInstanceByName() should not be called statically" in PHP indicates that you are attempting to call a non-static method as if it were static.
Understanding Static Methods
Static methods are class methods that can be called without instantiating an object of the class. They are declared using the static keyword. Static methods are typically used for utility functions or to access class properties.
Fixing the Error
In the provided code, the getInstanceByName() method in the Page class is not declared as static. To fix the error, add the static keyword to the method declaration:
public static function getInstanceByName($name='') { // Method implementation... }
After making this change, you should be able to call getInstanceByName() without receiving the error.
Testability Considerations
While static methods can be convenient, it is important to note that they can make unit testing more difficult. This is because static methods are not tied to specific instances of a class and therefore cannot be mocked or easily tested in isolation.
Querying in the Constructor
It is also worth mentioning that the Page class constructor contains excessive querying, which can impact performance and code readability. Consider refactoring the code to move the querying to a separate method or to inject the necessary data via dependency injection.
The above is the detailed content of How to Resolve the PHP Error: 'Non-Static Method Called Statically'?. For more information, please follow other related articles on the PHP Chinese website!