calling class method (with constructors) without object instantiation in php

前端 未结 4 1331
孤街浪徒
孤街浪徒 2020-12-16 04:15

Ive looked and tried but I can\'t find an answer.

In PHP, is it possible to call a class\' member function (when that class requires a constructor to receive parame

4条回答
  •  无人及你
    2020-12-16 04:50

    You can't call an instance-level method without an instance. Your syntax:

    echo Test("world")::alert("hello");
    

    doesn't make a lot of sense. Either you're creating an inline instance and discarding it immediately or the alert() method has no implicit this instance.

    Assuming:

    class Test {
      public function __construct($message) {
        $this->message = $message;
      }
    
      public function foo($message) {
        echo "$this->message $message";
      }
    }
    

    you can do:

    $t = new Test("Hello");
    $t->foo("world");
    

    but PHP syntax doesn't allow:

    new Test("Hello")->foo("world");
    

    which would otherwise be the equivalent. There are a few examples of this in PHP (eg using array indexing on a function return). That's just the way it is.

提交回复
热议问题