Home >Backend Development >PHP Tutorial >Why Does Calling a Non-Static Method Statically in PHP Result in an Error?

Why Does Calling a Non-Static Method Statically in PHP Result in an Error?

Susan Sarandon
Susan SarandonOriginal
2024-11-24 11:42:11853browse

Why Does Calling a Non-Static Method Statically in PHP Result in an Error?

Understanding Static Method Call Static Method Error

In PHP, the provided code snippet encounters the error message:

Strict standards: Non-static method
Page::getInstanceByName() should not
be called statically in
/var/www/webworks/index.php on line 12

This error occurs when a non-static method in the Page class is called statically, which is not allowed.

Fix

To resolve this issue, the getInstanceByName() method in the Page class needs to be declared as static. Modify the line:

function getInstanceByName($name='')

to:

public static function getInstanceByName($name='')

By declaring the method as static, you can call it using the class name, like:

$r = Page::getInstanceByName($page);

Additional Considerations

  • Static Methods and Testability: Static methods cannot be mocked or stubbed, which can make it difficult to test code that depends on them. Consider using dependency injection instead, where you pass data into the object through its constructor or methods.
  • Constructor Complexity: The constructor in the Page class is doing too much work, such as querying the database. Constructors should only be used to initialize the object's state, not to perform complex operations.

The above is the detailed content of Why Does Calling a Non-Static Method Statically in PHP Result in an Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn