search
HomeBackend DevelopmentPHP TutorialCan non-static methods be called statically in PHP? (weird call)

1. Can non-static methods be called statically in PHP?

Today I was asked whether I can use the className::methodName() method in PHP to call a method that is not declared static. In my mind, I seem to have seen this usage before, but I am a little unsure. As we all know, in manuals or tutorials, methods are divided into static methods and non-static methods. Usually the methods we call statically must be static methods.

What happens if we call a non-static method? Do the test first.

1 <?php

2 classtest{

​​​​​​'it works'
echo ;

5}6
​​​​​

}7
</td> <td> <code>
test::test();

8
?>

Execute the following, and the error returned is as follows:

1
Fatal error: Non-static method test::test() cannot be called statically in /home/×××/test.php
2

on line 7 Call Stack: 0.0002 332548 1. {main}() /home/×××/test.php:0

At this time, you may think that static calls are non-static The method will not work, but in fact, it is too early to draw the conclusion, because the test() method is quite special. It has the same name as the class and is a constructor method. Let's continue testing.

01
class test {

03

                                                              ​​
echo'it works' ;

test2() {
05                                                                                                                     function

07}
It works too'

</td> <td> <code>09}

10test::test2();

11
?> </td> <td> <code>This shows that statically calls non-static methods It is feasible, but statically calling the constructor method is not allowed. In order to verify this conclusion, I did the following test:

1

<?php </td> <td> <code>2
class

test{

</td> <td> <code>3

static

function
test() {

4

echo'it works' ;

5
6

}

test::test();
7

8
?></td> <td> <code>

The execution result is as follows:

1 Fatal error: Constructor test::test() cannot be static in /home/xxx/test.php on line 9

The constructor cannot be declared static, so the above inference is correct.

But this result is indeed very special, because maybe only PHP can statically call non-static methods. I did an experiment with Java. If you statically call a non-static method, the following error will be reported:

1 Cannot make a static reference to the non-static method showString() from the type HelloWorldApp

I have not tried other languages ​​one by one, but this is enough to illustrate the specialness of PHP However, I have not found any relevant explanation as to why PHP behaves like this.

2. Should static calls to non-static methods be applied?

So can we use this method instead of the static method? First of all, from the perspective of code readability, statically calling non-static methods is of course not recommended, which will make maintainers confused.

Next, let’s do some experiments to see if statically calling non-static methods has certain advantages in efficiency.

1 <?php

2 classtest{

3</td> <td> <code> functiontest2() { }

4 }

5

6</td> <td> <code>for(<code>$k=0; <code>$k<code>$k++) {

7</td> <td> <code> test::test2();

8 }

9 ?>

The execution of the above code here The time is 18 to 28 milliseconds. Let's test the standard writing method again.

1 <?php

2 classtest{

3</td> <td> <code> staticfunctiontest2(){ }

4 }

5

6</td> <td> <code>for(<code>$k=0; <code>$k<code>$k++) {

7</td> <td> <code> test::test2();

8 }

9 ?>

The above code execution time is 5 to 10 milliseconds. From this point of view, the efficiency of statically calling non-static methods is much lower than standard static method calls, so statically calling non-static methods is not recommended in terms of efficiency.

I found that WordPress actually uses such a weird calling method:

class-wp.php Lines 206-207:
// Substitute the substring matches into the query.$query = addslashes(WP_MatchesMapRegex:: apply($query, $matches));

Static calling is used here, but the actual member function is not static.


Note: PHP cannot statically call non-static properties

1 <?php

2class
test{

3
var$id= '123' ;

4​​

functiontest2() {
6
5 }

7}

8test:: ;
echo$id

9
?>
Error: Access

The above introduces whether non-static methods can be called statically in PHP? (Weird call), including aspects of the content, I hope it will be helpful to friends who are interested in PHP tutorials.
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use