0

在 PHP 中,是否可以在非静态类中拥有一个函数,但也不是实例函数?

例如,如果我有以下内容:

class A
{
   public $i;

   function setValue($val) {
      $this->i = $val;
   }
}  

$a1 = new A;
$a1->setValue(5);
echo $a1->i; // result: 5

$a2 = new A;
$a2->setValue(2);
echo $a2->i; // result: 2

我可以向该类添加一个函数,该函数可以对自身的所有实例具有“可见性”,以便我可以执行类似的操作(我知道这不起作用,但可以传达我的想法):

class A
{
   public $i;

   function setValue($val) {
      $this->i = $val;
   }

   function getTotal() {
      return sum($this->i); // I know sum() isn't a built-in function, but it helps explain what I want. I'm not sure if $this makes sense here too.
   }
}  

$a1 = new A;
$a1->setValue(5);
echo $a1->i; // result: 5

$a2 = new A;
$a2->setValue(2);
echo $a2->i; // result: 2

echo A::getTotal(); // returns: 7

我猜A::getTotal()手段getTotal()需要是静态的,但如果它是静态的,那么它将无法“看到”每个类实例。

这种事情可能吗,我应该使用什么正确的术语?

4

4 回答 4

4

不,没有内置的实例枚举,您需要自己保留对每个实例化对象的引用。您可以在类的静态属性中保留一个实例数组,并将其填充到您的__construct(). 然后,您可以对该数组进行静态方法循环并处理所有实例。

于 2012-07-03T13:25:48.720 回答
1

I think you would like something like this:

 class A
{
   public $i;

   function setValue($val) {
      $this->i = $val;
   }
}  

$a1 = new A;
$a1->setValue(5);
echo $a1->i; // result: 5

$a2 = new A;
$a2->setValue(2);
echo $a2->i; // result: 2

$total = 0;
foreach( get_defined_vars() as $name => $obj ) {
  if ( $obj instanceof A ) {
    $total += $obj->i;
  }
}
echo $total; // returns: 7

The function you need here is "get_defined_vars". But it only gets the variables within the current scope!

于 2012-07-03T13:48:52.140 回答
0

只需将 sum 的类成员设为静态即可。如果您这样做,那么您将需要确保它在每个类中得到正确维护(即setValue需要适当地更新该总和)。

不过,这可能不是做事的好方法。我认为它会变得相当混乱。在什么情况下您需要您无法访问所有实例的总和?

于 2012-07-03T13:31:47.250 回答
0

您是否正在寻找protected function foo($s){...}类可以使用但不能从外部访问的类?(仅限 PHP5)

于 2012-07-03T14:53:17.417 回答