doutao6380 2012-07-03 13:23
浏览 63
已采纳

在PHP中,是否可以在非静态类中使用函数,但也不是实例函数?

In PHP, is it possible to have a function within a class that's non-static, but also isn't an instance function?

For example, if I have the following:

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

Can I add a function to that class that can have "visibility" of all instances of itself so I can do something like so (which I know doesn't work, but communicates my thought):

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

I guess A::getTotal() means getTotal() would need to be static, but if it was static then it wouldn't then be able to "see" each class instance.

Is this type of thing possible, and what's the correct terminology I should be using?

  • 写回答

4条回答 默认 最新

  • douhui0975 2012-07-03 13:25
    关注

    No, there is no built-in instance enumeration, you will need to keep references to each instantiated object yourself. You can keep an array of instances in a static property of the class and populate it in your __construct(). You can then have a static method loop over this array and process all instances.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题