Non-static method ..... should not be called statically
Asked Answered
L

4

77

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

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:

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

I hope somebody can help.

Legatee answered 30/10, 2013 at 21:15 Comment(0)
N
145

That means it should be called like:

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

The difference between static and non-static is that the first one doesn't need instantiation so you can call the classname then append :: to it and call the method immediately. Like so:

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:

(new ClassName)->method();
Nunciata answered 30/10, 2013 at 21:23 Comment(5)
Or perhaps he should change the method to be static (since this is an existing codebase now being run in an upgraded PHP environment).Laborsaving
@mamdouh You are great, the error is gone. Thank you for your help. Have a nice evening. sincerely, JacoLegatee
@user2938848 - you are welcome. I hope you mark the answer as accepted, as it works with you :)Nunciata
By faster calling : (new ClassName)->method(); you mean shorthand. Right?Severus
Im sure that syntax is the intention.Building
S
23

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

class Handler {
    public static function helloWorld() {
        echo "Hello world!";
    }
}
Shanon answered 21/6, 2016 at 4:42 Comment(0)
R
8

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.

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.

Rectal answered 1/5, 2020 at 11:53 Comment(0)
B
3
public function functionName($variable)

Change to

public static function functionName($variable)
Bullhead answered 3/6, 2022 at 11:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.