Calling non-static method with double-colon(::)

Viewed 53710

Why can't I use a method non-static with the syntax of the methods static(class::method) ? Is it some kind of configuration issue?

class Teste {

    public function fun1() {
        echo 'fun1';
    }
    public static function fun2() {
        echo "static fun2" ;
    }
}

Teste::fun1(); // why?
Teste::fun2(); //ok - is a static method
11 Answers

Warning In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.

Link

Starting on PHP8, this no longer works.

The ability to call non-static methods statically was finally removed in PHP 8.

The ability to call non-static methods statically has been removed. Thus is_callable() will fail when checking for a non-static method with a classname (must check with an object instance).

It was originally deprecated on PHP 7.

Static calls to methods that are not declared static are deprecated, and may be removed in the future.

One way for calling the same method both statically and non-statically is using the magic methods __call and __callStatic.

The FluentMath class (code down below) is an example where you can invoke the methods add or subtract both statically and not:

$res1 = FluentMath::add(5)    // add method called statically
    ->add(3)                  // add method called non-statically
    ->subtract(2)
    ->result();

$res2 = FluentMath::subtract(1)->add(10)->result();

FluentMath class

class FluentMath
{
    private $result = 0;

    public function __call($method, $args)
    {
        return $this->call($method, $args);
    }

    public static function __callStatic($method, $args)
    {
        return (new static())->call($method, $args);
    }

    private function call($method, $args)
    {
        if (! method_exists($this , '_' . $method)) {
            throw new Exception('Call undefined method ' . $method);
        }

        return $this->{'_' . $method}(...$args);
    }

    private function _add($num)
    {
        $this->result += $num;

        return $this;
    }

    private function _subtract($num)
    {
        $this->result -= $num;

        return $this;
    }

    public function result()
    {
        return $this->result;
    }
}

If you want the full explanation of how that class works please check:

Related