duanchuonong5370 2016-09-06 08:41
浏览 141
已采纳

使用私有静态方法

I am trying to work out whether the private static method in the example below should be non-static. It is only concerned with the static properties of the class which leads me to believe it is okay as a static method. However, it is only invoked from a non-static method, which suggests it should be a non-static method too.

I understand when a public method should be static, but not when a private method should be static.

Thanks in advance for your advice!

<?php
class MyClass
{
    private static $initialized = false;
    private static $staticProperty1;
    private static $staticProperty2;
    private        $normalProperty1;

    public function __construct($normalProperty)
    {
        $this->normalProperty1 = $normalProperty;
    }

    public function doSomething()
    {
        self::initialize();
        // Now do some other stuff
    }

    private static function initialize()
    {
        if (!self::$initialized) {
            self::$staticProperty1 = 'Hello';
            self::$staticProperty2 = 'World';
            self::$initialized = true;
        }
    }
}
  • 写回答

2条回答 默认 最新

  • douchun5976 2016-09-06 08:58
    关注

    This is an interesting question. You want to know when a private function should be static. It has to be static if you want to call it from another static method. That is because you do not have access to $this.

    My previous assumption was not correct. You can also call a non static method from a static function. But you have to consider that you do not have access to the object itself with the variable $this. Also it is not possible to access non static object properties.

    In your example, in my opinion if you call the method from a non static context anyway, you can make it not static. There is no need for it to be static. But I cannot tell you if this is good practice. Just what I would do.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?