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

Susan Sarandon
Release: 2024-11-24 11:42:11
Original
828 people have browsed it

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
Copy after login

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='')
Copy after login

to:

public static function getInstanceByName($name='')
Copy after login

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

$r = Page::getInstanceByName($page);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template