php 非静态方法 ..... 不应静态调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19693946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:52:06  来源:igfitidea点击:

Non-static method ..... should not be called statically

phpstaticnon-static

提问by Novice Hobby PHP Boy

I have recently done an update to PHP 5.4, and I get an error about static and non-static code.

我最近对 ​​PHP 5.4 进行了更新,但出现关于静态和非静态代码的错误。

This is the error:

这是错误:

PHP Strict Standards:  Non-static method VTimer::get() 
should not be called statically in /home/jaco/public_html/include/function_smarty.php on line 371

This is the line 371:

这是第 371 行:

$timer  = VTimer::get($options['magic']);

I hope somebody can help.

我希望有人可以提供帮助。

回答by mamdouh alramadan

That means it should be called like:

这意味着它应该被称为:

$timer = (new VTimer)->get($options['magic']);

$timer = (new VTimer)->get($options['magic']);

The difference between staticand non-staticis that the first one doesn't need initialization so you can call the classnamethen append ::to it and call the method immediately. Like so:

static和之间的区别在于non-static第一个不需要初始化,因此您可以调用classnamethen 附加::到它并立即调用该方法。像这样:

ClassName::method();

and if the method is not static you need to initialize it like so:

如果该方法不是静态的,则需要像这样初始化它:

$var = new ClassName();
$var->method();

However, in PHP 5.4 you can use this syntax instead as a shorthand:

但是,在 PHP 5.4 中,您可以使用以下语法作为速记:

(new ClassName)->method();

回答by deadghost

You can also change the method to be static like so:

您还可以将方法更改为静态,如下所示:

class Handler {
    public static function helloWorld() {
        echo "Hello world!";
    }
}

回答by Particle Effect

The most elegant way would be :

最优雅的方式是:

(new ClassName)->method();

You can also convert your function to static function call() {}, but that depends on your function and what you're doing with it.

您也可以将您的函数转换为static function call() {},但这取决于您的函数以及您使用它做什么。

If you need to instantiate a class then avoid doing so, treat static functions like constants, they can not have objects and require predefined variables.

如果您需要实例化一个类,请避免这样做,将静态函数视为常量,它们不能有对象并需要预定义的变量。