在 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()
需要是静态的,但如果它是静态的,那么它将无法“看到”每个类实例。
这种事情可能吗,我应该使用什么正确的术语?