在php中调用没有对象实例化的类方法(带构造函数)

myk*_*k00 6 php methods constructor class instantiation

我看了又试过但我找不到答案.

在PHP中,是否可以调用类的成员函数(当该类需要构造函数来接收参数时)而不将其实例化为对象?

一个代码示例(给出错误):

<?php

class Test {
    private $end="";

    function __construct($value) {
        $this->end=$value;
    }

    public function alert($value) {
        echo $value." ".$this->end;
    }
}

//this works:
$example=new Test("world");
$example->alert("hello");

//this does not work:
echo Test("world")::alert("hello");

?>
Run Code Online (Sandbox Code Playgroud)

Fel*_*ins 21

不幸的是,PHP没有支持这样做,但你是一个富有创造力的人:D

您可以使用"工厂",示例:

<?php

class Foo
{
   private $__aaa = null;

   public function __construct($aaa)
   {
      $this->__aaa = $aaa;
   }

   public static function factory($aaa)
   {
      return new Foo($aaa);
   }

   public function doX()
   {
      return $this->__aaa * 2;
   }
}

Foo::factory(10)->doX();   // outputs 20
Run Code Online (Sandbox Code Playgroud)


And*_*w U 7

这样做(在PHP> = 5.4):

$t = (new Test("Hello"))->foo("world");
Run Code Online (Sandbox Code Playgroud)


cle*_*tus 1

如果没有实例,则无法调用实例级方法。你的语法:

echo Test("world")::alert("hello");
Run Code Online (Sandbox Code Playgroud)

没有多大意义。要么您正在创建一个内联实例并立即丢弃它,要么该alert()方法没有隐式this实例。

假设:

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

  public function foo($message) {
    echo "$this->message $message";
  }
}
Run Code Online (Sandbox Code Playgroud)

你可以做:

$t = new Test("Hello");
$t->foo("world");
Run Code Online (Sandbox Code Playgroud)

但 PHP 语法不允许:

new Test("Hello")->foo("world");
Run Code Online (Sandbox Code Playgroud)

否则是等价的。PHP 中有一些这样的例子(例如,在函数返回上使用数组索引)。就是那样子。