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

时间:2010-06-23 04:06:26

标签: php class constructor methods 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");

?>

5 个答案:

答案 0 :(得分:19)

不幸的是,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

答案 1 :(得分:6)

这样做(在PHP&gt; = 5.4中):

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

答案 2 :(得分:1)

我也在寻找一个单行代码来实现这一点,作为将日期从一种格式转换为另一种格式的单个表达式的一部分。我喜欢在一行代码中执行此操作,因为它是单个逻辑操作。所以,这有点神秘,但它允许您在一行中实例化和使用日期对象:

$newDateString = ($d = new DateTime('2011-08-30') ? $d->format('F d, Y') : '');

将日期字符串从一种格式转换为另一种格式的另一种方法是使用辅助函数来管理代码的OO部分:

function convertDate($oldDateString,$newDateFormatString) {
    $d = new DateTime($oldDateString);
    return $d->format($newDateFormatString);
}

$myNewDate = convertDate($myOldDate,'F d, Y');

我认为面向对象的方法很酷且必要,但它有时可能很乏味,需要太多步骤才能完成简单的操作。

答案 3 :(得分:0)

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

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

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

假设:

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

  public function foo($message) {
    echo "$this->message $message";
  }
}

你可以这样做:

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

但PHP语法不允许:

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

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

答案 4 :(得分:0)

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

// works, as you are calling not to an object of the class, but to its namespace
echo Test::alert("hello");